'use client';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { api } from '@/lib/api';
import { useAuthStore } from '@/lib/auth-store';
import { useLanguage } from '@/lib/language-context';
import { CreditCard, Gift, Mail, Search, Users } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
import PaginationControls from '@/components/common/PaginationControls';

interface Registration {
    _id: string;
    firstName: string;
    lastName: string;
    email: string;
    phone?: string;
    userType: string;
    isActive: boolean;
    ownerId?: string | null;
    accountType?: 'Primary Doctor' | 'Teammate';
    primaryDoctor?: {
        _id?: string;
        firstName?: string;
        lastName?: string;
        email?: string;
    } | null;
    clinic?: { name?: string; address?: string };
    registeredAt: string;
    subscription: {
        _id: string;
        status: string;
        startDate: string;
        endDate: string;
        category: string;
    } | null;
    plan: {
        _id: string;
        title: string;
        price: number;
        period: string;
    } | null;
    isFree: boolean;
}

interface Stats {
    total: number;
    free: number;
    paid: number;
    byPlan: Record<string, number>;
}

interface PlanOption {
    _id: string;
    title: string;
    price: number;
    period: string;
}

type FilterType = 'all' | 'free' | 'paid';

const subscriptionStatusColors: Record<string, string> = {
    Active: 'bg-green-100 text-green-800',
    PastDue: 'bg-yellow-100 text-yellow-800',
    Cancelled: 'bg-red-100 text-red-800',
    Expired: 'bg-slate-100 text-slate-600',
};

const getPlanTitleLabel = (title: string | undefined, t: (key: string) => string) => {
    if (!title) return '';
    const normalized = title.trim().toLowerCase();
    if (normalized === 'annual plan') return t('adminRegistrations.annualPlan');
    if (normalized === 'monthly plan') return t('adminRegistrations.monthlyPlan');
    if (normalized === 'free forever') return t('subscriptionPage.freeForever');
    return title;
};

const getPlanPeriodLabel = (period: string | undefined, t: (key: string) => string) => {
    if (!period) return '';
    const normalized = period.trim().toLowerCase();
    if (normalized === 'annual' || normalized === 'yearly' || normalized === 'year') return t('adminRegistrations.annual');
    if (normalized === 'monthly' || normalized === 'month') return t('adminRegistrations.monthly');
    if (normalized === 'freely' || normalized === 'lifetime') return t('adminRegistrations.lifetime');
    return period;
};

const getSubscriptionStatusLabel = (status: string | undefined, t: (key: string) => string) => {
    if (!status) return '';
    const normalized = status.trim().toLowerCase();
    if (normalized === 'active') return t('subscriptionPage.active');
    if (normalized === 'pastdue') return t('subscriptionPage.pastDue');
    if (normalized === 'cancelled') return t('subscriptionPage.cancelled');
    if (normalized === 'expired') return t('subscriptionPage.expired');
    return status;
};

export default function AdminRegistrationsPage() {
    const { t } = useLanguage();
    const { token, user } = useAuthStore();
    const router = useRouter();

    const [registrations, setRegistrations] = useState<Registration[]>([]);
    const [stats, setStats] = useState<Stats | null>(null);
    const [loading, setLoading] = useState(true);
    const [search, setSearch] = useState('');
    const [filter, setFilter] = useState<FilterType>('all');
    const [plans, setPlans] = useState<PlanOption[]>([]);
    const [editTarget, setEditTarget] = useState<Registration | null>(null);
    const [selectedPlanId, setSelectedPlanId] = useState('');
    const [savingPlan, setSavingPlan] = useState(false);
    const [actionError, setActionError] = useState('');
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);

    const fetchRegistrations = useCallback(async () => {
        if (!token) return;
        try {
            const res = await api.admin.getRegistrations(token);
            if (res.success && res.data) {
                setRegistrations(res.data.registrations || []);
                setStats(res.data.stats || null);
            }
        } catch (err) {
            console.error('Error fetching registrations:', err);
        } finally {
            setLoading(false);
        }
    }, [token]);

    const fetchPlans = useCallback(async () => {
        if (!token) return;
        const res = await api.admin.getPlans(token);
        if (res.success && Array.isArray(res.data)) {
            setPlans(res.data as PlanOption[]);
        }
    }, [token]);

    useEffect(() => {
        if (!user || user.userType !== 'admin') {
            router.replace('/dashboard');
            return;
        }
        fetchRegistrations();
        fetchPlans();
    }, [user, router, fetchRegistrations, fetchPlans]);

    const openEditSubscription = (reg: Registration) => {
        setActionError('');
        setEditTarget(reg);
        setSelectedPlanId(reg.plan?._id || '');
    };

    const handleSaveSubscription = async () => {
        if (!token || !editTarget || !selectedPlanId) return;
        setSavingPlan(true);
        setActionError('');

        const res = await api.admin.updateSubscription(token, editTarget._id, selectedPlanId);
        if (!res.success) {
            setActionError(res.error || t('adminRegistrations.failedToUpdateSubscription'));
            setSavingPlan(false);
            return;
        }

        await fetchRegistrations();
        setSavingPlan(false);
        setEditTarget(null);
    };

    const filtered = registrations.filter((r) => {
        const q = search.toLowerCase();
        const matchesSearch =
            !q ||
            r.firstName.toLowerCase().includes(q) ||
            r.lastName.toLowerCase().includes(q) ||
            r.email.toLowerCase().includes(q) ||
            (r.clinic?.name ?? '').toLowerCase().includes(q);

        const matchesFilter =
            filter === 'all' ||
            (filter === 'free' && r.isFree) ||
            (filter === 'paid' && !r.isFree);

        return matchesSearch && matchesFilter;
    });

    useEffect(() => {
        setCurrentPage(1);
    }, [search, filter, pageSize]);

    const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
    const paginated = filtered.slice((currentPage - 1) * pageSize, currentPage * pageSize);

    useEffect(() => {
        if (currentPage > totalPages) {
            setCurrentPage(totalPages);
        }
    }, [currentPage, totalPages]);

    if (!user || user.userType !== 'admin') return null;

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex flex-col gap-1">
                <h1 className="text-3xl font-bold tracking-tight flex items-center gap-2">
                    <Mail className="w-7 h-7 text-cyan-600" />
                    {t('adminRegistrations.title')}
                </h1>
                <p className="text-muted-foreground text-sm">{t('adminRegistrations.description')}</p>
            </div>

            {/* Stats Cards */}
            {stats && (
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <Card className="border-cyan-100 shadow-sm">
                        <CardContent className="pt-6 flex items-center gap-4">
                            <div className="p-3 bg-cyan-50 rounded-xl">
                                <Users className="w-6 h-6 text-cyan-600" />
                            </div>
                            <div>
                                <p className="text-sm text-muted-foreground">{t('adminRegistrations.totalRegistrations')}</p>
                                <p className="text-3xl font-bold text-cyan-700">{stats.total}</p>
                            </div>
                        </CardContent>
                    </Card>

                    <Card className="border-green-100 shadow-sm">
                        <CardContent className="pt-6 flex items-center gap-4">
                            <div className="p-3 bg-green-50 rounded-xl">
                                <Gift className="w-6 h-6 text-green-600" />
                            </div>
                            <div>
                                <p className="text-sm text-muted-foreground">{t('adminRegistrations.freeRegistrations')}</p>
                                <p className="text-3xl font-bold text-green-700">{stats.free}</p>
                            </div>
                        </CardContent>
                    </Card>

                    <Card className="border-blue-100 shadow-sm">
                        <CardContent className="pt-6 flex items-center gap-4">
                            <div className="p-3 bg-blue-50 rounded-xl">
                                <CreditCard className="w-6 h-6 text-blue-600" />
                            </div>
                            <div>
                                <p className="text-sm text-muted-foreground">{t('adminRegistrations.paidRegistrations')}</p>
                                <p className="text-3xl font-bold text-blue-700">{stats.paid}</p>
                            </div>
                        </CardContent>
                    </Card>
                </div>
            )}

            {/* Plan Distribution */}
            {stats && Object.keys(stats.byPlan).length > 0 && (
                <Card className="shadow-sm">
                    <CardHeader className="pb-3">
                        <CardTitle className="text-base">{t('adminRegistrations.planDistribution')}</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="flex flex-wrap gap-3">
                            {Object.entries(stats.byPlan).map(([planName, count]) => (
                                <div
                                    key={planName}
                                    className="flex items-center gap-2 bg-slate-50 border border-slate-200 rounded-lg px-4 py-2"
                                >
                                    <span className="font-semibold text-slate-700">{getPlanTitleLabel(planName, t)}</span>
                                    <span className="text-xs bg-cyan-100 text-cyan-800 px-2 py-0.5 rounded-full font-bold">{count}</span>
                                </div>
                            ))}
                        </div>
                    </CardContent>
                </Card>
            )}

            {/* Table */}
            <Card className="shadow-sm">
                <CardHeader className="pb-4">
                    <div className="flex flex-col sm:flex-row gap-3 items-start sm:items-center">
                        {/* Search */}
                        <div className="relative flex-1 max-w-sm">
                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                            <Input
                                className="pl-9"
                                placeholder={t('adminRegistrations.searchPlaceholder')}
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                            />
                        </div>

                        {/* Filter tabs */}
                        <div className="flex gap-1 bg-slate-100 rounded-lg p-1">
                            {(['all', 'free', 'paid'] as FilterType[]).map((f) => (
                                <button
                                    key={f}
                                    onClick={() => setFilter(f)}
                                    className={`px-3 py-1.5 rounded-md text-sm font-medium transition-all ${filter === f
                                            ? 'bg-white text-cyan-700 shadow-sm'
                                            : 'text-slate-600 hover:text-slate-900'
                                        }`}
                                >
                                    {f === 'all' && t('adminRegistrations.filterAll')}
                                    {f === 'free' && t('adminRegistrations.filterFree')}
                                    {f === 'paid' && t('adminRegistrations.filterPaid')}
                                </button>
                            ))}
                        </div>
                    </div>
                </CardHeader>

                <CardContent className="p-0">
                    {!loading && filtered.length > 0 && (
                        <PaginationControls
                            currentPage={currentPage}
                            totalPages={totalPages}
                            onPageChange={setCurrentPage}
                            maxPageButtons={5}
                            alignment="right"
                            showSummary={false}
                            showPageSize={false}
                            className="border-b px-4 py-3"
                            labels={{
                                showing: t('common.showing'),
                                to: t('common.to'),
                                of: t('common.of'),
                                perPage: t('common.perPage'),
                                previous: t('common.previous'),
                                next: t('common.next'),
                            }}
                        />
                    )}
                    <div className="rounded-b-xl overflow-x-auto">
                        <Table>
                            <TableHeader>
                                <TableRow className="bg-slate-50">
                                    <TableHead>{t('adminRegistrations.colName')}</TableHead>
                                    <TableHead>{t('adminRegistrations.colEmail')}</TableHead>
                                    <TableHead>{t('adminRegistrations.colClinic')}</TableHead>
                                    <TableHead>{t('adminRegistrations.colPlan')}</TableHead>
                                    <TableHead>{t('adminRegistrations.colSubscriptionStatus')}</TableHead>
                                    <TableHead>{t('adminRegistrations.colRegistered')}</TableHead>
                                    <TableHead>{t('adminRegistrations.actions')}</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {loading ? (
                                    <TableRow>
                                        <TableCell colSpan={7} className="text-center py-10 text-muted-foreground">
                                            {t('adminRegistrations.loading')}
                                        </TableCell>
                                    </TableRow>
                                ) : filtered.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={7} className="text-center py-10 text-muted-foreground">
                                            {t('adminRegistrations.noResults')}
                                        </TableCell>
                                    </TableRow>
                                ) : (
                                    paginated.map((reg) => (
                                        <TableRow key={reg._id} className="hover:bg-slate-50/50">
                                            <TableCell className="font-medium whitespace-nowrap">
                                                <div className="flex items-center gap-2">
                                                    <span>{reg.firstName} {reg.lastName}</span>
                                                    <span className={`text-xs px-2 py-0.5 rounded-full font-semibold ${reg.accountType === 'Teammate'
                                                            ? 'bg-slate-100 text-slate-700'
                                                            : 'bg-cyan-100 text-cyan-800'
                                                        }`}>
                                                        {reg.accountType === 'Teammate'
                                                            ? t('adminRegistrations.teammate')
                                                            : t('adminRegistrations.primaryDoctor')}
                                                    </span>
                                                    {reg.isFree && (
                                                        <span className="text-xs bg-green-100 text-green-700 px-1.5 py-0.5 rounded-full font-semibold">
                                                            {t('adminRegistrations.freeBadge')}
                                                        </span>
                                                    )}
                                                </div>
                                                {reg.accountType === 'Teammate' && reg.primaryDoctor && (
                                                    <div className="text-xs text-slate-500 mt-1">
                                                        {t('common.primaryDoctor')}: {reg.primaryDoctor.firstName} {reg.primaryDoctor.lastName}
                                                    </div>
                                                )}
                                            </TableCell>
                                            <TableCell className="text-slate-600">{reg.email}</TableCell>
                                            <TableCell className="text-slate-600">
                                                {reg.clinic?.name || <span className="text-slate-400 text-xs">—</span>}
                                            </TableCell>
                                            <TableCell>
                                                {reg.plan ? (
                                                    <div className="flex flex-col">
                                                        <span className="font-medium text-sm">{getPlanTitleLabel(reg.plan.title, t)}</span>
                                                        <span className="text-xs text-muted-foreground">{getPlanPeriodLabel(reg.plan.period, t)}</span>
                                                    </div>
                                                ) : (
                                                    <span className="text-slate-400 text-xs">{t('adminRegistrations.noPlan')}</span>
                                                )}
                                            </TableCell>
                                            <TableCell>
                                                {reg.subscription ? (
                                                    <span
                                                        className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${subscriptionStatusColors[reg.subscription.status] || 'bg-slate-100 text-slate-600'
                                                            }`}
                                                    >
                                                        {getSubscriptionStatusLabel(reg.subscription.status, t)}
                                                    </span>
                                                ) : (
                                                    <span className="text-slate-400 text-xs">—</span>
                                                )}
                                            </TableCell>
                                            <TableCell className="text-slate-500 text-sm whitespace-nowrap">
                                                {new Date(reg.registeredAt).toLocaleDateString()}
                                            </TableCell>
                                            <TableCell>
                                                <Button
                                                    size="sm"
                                                    variant="outline"
                                                    onClick={() => openEditSubscription(reg)}
                                                >
                                                    {t('adminRegistrations.editSubscription')}
                                                </Button>
                                            </TableCell>
                                        </TableRow>
                                    ))
                                )}
                            </TableBody>
                        </Table>
                    </div>
                    {!loading && filtered.length > 0 && (
                        <PaginationControls
                            currentPage={currentPage}
                            totalPages={totalPages}
                            onPageChange={setCurrentPage}
                            maxPageButtons={5}
                            pageSize={pageSize}
                            pageSizeOptions={[10, 20, 50]}
                            onPageSizeChange={(size) => setPageSize(size)}
                            showingFrom={(currentPage - 1) * pageSize + 1}
                            showingTo={Math.min(currentPage * pageSize, filtered.length)}
                            totalItems={filtered.length}
                            labels={{
                                showing: t('common.showing'),
                                to: t('common.to'),
                                of: t('common.of'),
                                perPage: t('common.perPage'),
                                previous: t('common.previous'),
                                next: t('common.next'),
                            }}
                        />
                    )}
                </CardContent>
            </Card>

            <Dialog open={!!editTarget} onOpenChange={(open) => !open && setEditTarget(null)}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>{t('adminRegistrations.editSubscription')}</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4">
                        <div>
                            <p className="text-sm text-muted-foreground">{t('adminRegistrations.user')}</p>
                            <p className="font-medium">{editTarget?.firstName} {editTarget?.lastName}</p>
                            <p className="text-sm text-muted-foreground">{editTarget?.email}</p>
                        </div>
                        <div className="space-y-2">
                            <Label>{t('adminRegistrations.colPlan')}</Label>
                            <Select value={selectedPlanId} onValueChange={setSelectedPlanId}>
                                <SelectTrigger>
                                    <SelectValue placeholder={t('adminRegistrations.selectPlan')} />
                                </SelectTrigger>
                                <SelectContent>
                                    {plans.map((plan) => (
                                        <SelectItem key={plan._id} value={plan._id}>
                                            {getPlanTitleLabel(plan.title, t)} {plan.price > 0 ? `— $${plan.price}/${getPlanPeriodLabel(plan.period, t)}` : `— ${getPlanPeriodLabel(plan.period, t)}`}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                        {actionError && (
                            <p className="text-sm text-red-600">{actionError}</p>
                        )}
                    </div>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setEditTarget(null)} disabled={savingPlan}>
                            {t('common.cancel')}
                        </Button>
                        <Button onClick={handleSaveSubscription} disabled={savingPlan || !selectedPlanId}>
                            {savingPlan ? t('common.saving') : t('common.save')}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    );
}
