'use client';

import Pricing from '@/components/landing/Pricing';
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 {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import ConfirmDialog from '@/components/common/ConfirmDialog';
import { api } from '@/lib/api';
import { AuthService } from '@/lib/auth-service';
import { useAuthStore } from '@/lib/auth-store';
import { useLanguage } from '@/lib/language-context';
import { Check, Edit2, Loader2, RotateCcw, ShieldCheck } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { toast } from 'sonner';

interface SubscriptionItem {
    _id?: string;
    planId?: {
        _id?: string;
        period?: string;
        title?: string;
    } | string;
    status?: string;
    endDate: string;
}

interface PlanItem {
    _id: string;
    title: string;
    price: number;
    period: string;
    features: string[];
    createdAt?: string;
    updatedAt?: string;
}

const PERIOD_OPTIONS = [
    { value: 'monthly', labelKey: 'adminPlans.monthly' },
    { value: '6-month', labelKey: 'adminPlans.sixMonth' },
    { value: 'annual', labelKey: 'adminPlans.annual' },
    { value: 'freely', labelKey: 'adminPlans.freely' },
    { value: 'trial', labelKey: 'adminPlans.trial' },
];

const getPeriodLabel = (period: string, t: (key: string) => string) => {
    const opt = PERIOD_OPTIONS.find((o) => o.value === period);
    return opt ? t(opt.labelKey) : period;
};

const getPlanTitleLabel = (title: string | undefined, t: (key: string) => string) => {
    if (!title) return '';
    const normalized = title.trim().toLowerCase();
    if (normalized === 'annual plan') return t('adminPlans.annualPlanTitle');
    if (normalized === 'monthly plan') return t('adminPlans.monthlyPlanTitle');
    if (normalized === '6 month plan') return t('adminPlans.sixMonthPlanTitle');
    if (normalized === 'free forever') return t('adminPlans.freeForeverTitle');
    if (normalized === 'free trial' || normalized === 'free trials') return t('adminPlans.freeTrialTitle');
    return title;
};

export default function SubscriptionPage() {
    const { t } = useLanguage();
    const { user, setHasActiveSubscription } = useAuthStore();
    const [loading, setLoading] = useState(true);
    const [subscriptions, setSubscriptions] = useState<SubscriptionItem[]>([]);
    const [cancelDialogOpen, setCancelDialogOpen] = useState(false);
    const [cancelLoading, setCancelLoading] = useState(false);

    // Admin plan management state
    const [adminPlans, setAdminPlans] = useState<PlanItem[]>([]);
    const [editDialogOpen, setEditDialogOpen] = useState(false);
    const [editingPlan, setEditingPlan] = useState<PlanItem | null>(null);
    const [formPrice, setFormPrice] = useState('');
    const [formError, setFormError] = useState('');
    const [saving, setSaving] = useState(false);
    const [resetDialogOpen, setResetDialogOpen] = useState(false);
    const [resetting, setResetting] = useState(false);
    const [planError, setPlanError] = useState('');
    const resetPlansLabel = t('adminPlans.resetPlans') === 'adminPlans.resetPlans' ? 'Reset Plans' : t('adminPlans.resetPlans');
    const resetConfirmTitle = t('adminPlans.resetConfirmTitle') === 'adminPlans.resetConfirmTitle'
        ? 'Reset all plans?'
        : t('adminPlans.resetConfirmTitle');
    const resetConfirmDescription = t('adminPlans.resetConfirmDescription') === 'adminPlans.resetConfirmDescription'
        ? 'This will restore plans from seedPlans and remove custom plan changes.'
        : t('adminPlans.resetConfirmDescription');

    const fetchSubscriptions = async () => {
        const token = AuthService.getToken();
        if (token) {
            try {
                const res = await api.subscription.getMySubscription(token);
                if (res.success) {
                    const data = Array.isArray(res.data)
                        ? res.data as SubscriptionItem[]
                        : (res.data ? [res.data as SubscriptionItem] : []);
                    setSubscriptions(data);
                }
            } catch (error) {
                console.error("Failed to fetch subscription", error);
            } finally {
                setLoading(false);
            }
        } else {
            setLoading(false);
        }
    };

    const fetchAdminPlans = useCallback(async () => {
        const token = AuthService.getToken();
        if (!token) return;
        const res = await api.admin.getPlans(token);
        if (res.success && Array.isArray(res.data)) {
            setAdminPlans(res.data as PlanItem[]);
        }
    }, []);

    useEffect(() => {
        fetchSubscriptions();
    }, [user]);

    useEffect(() => {
        if (user?.userType === 'admin') {
            fetchAdminPlans();
        }
    }, [user, fetchAdminPlans]);

    const openEditDialog = (plan: PlanItem) => {
        setEditDialogOpen(true);
        setEditingPlan(plan);
        setFormPrice(String(plan.price));
        setFormError('');
    };

    const closeDialog = () => {
        setEditDialogOpen(false);
        setEditingPlan(null);
        setFormError('');
    };

    const handleSavePlan = async () => {
        const token = AuthService.getToken();
        if (!token || !editingPlan) return;
        setFormError('');

        if (!formPrice || Number.isNaN(Number(formPrice)) || Number(formPrice) < 0) {
            setFormError(t('adminPlans.validPriceRequired'));
            return;
        }
        setSaving(true);

        const res = await api.plans.update(token, editingPlan._id, {
            price: Number(formPrice),
        });
        if (!res.success) {
            setFormError(res.error || t('adminPlans.failedUpdate'));
            setSaving(false);
            return;
        }

        setSaving(false);
        closeDialog();
        await fetchAdminPlans();
    };

    const handleResetPlans = async () => {
        const token = AuthService.getToken();
        if (!token) return;
        setResetting(true);
        setPlanError('');
        const res = await api.plans.reset(token);
        if (!res.success) {
            setPlanError(res.error || t('adminPlans.failedReset'));
            setResetting(false);
            setResetDialogOpen(false);
            return;
        }
        toast.success(t('adminPlans.resetSuccess'));
        setResetting(false);
        setResetDialogOpen(false);
        await fetchAdminPlans();
    };

    const handleCancelSubscription = async () => {
        const token = AuthService.getToken();
        if (!token) return;
        setCancelLoading(true);
        try {
            const res = await api.subscription.cancel(token, currentSubscription?._id);
            if (!res.success) {
                toast.error(res.error || t('subscriptionPage.cancelFailed'));
                return;
            }
            toast.success(t('subscriptionPage.cancelSuccess'));
            setHasActiveSubscription(false);
            setCancelDialogOpen(false);
            await fetchSubscriptions();
        } catch {
            toast.error(t('subscriptionPage.cancelFailed'));
        } finally {
            setCancelLoading(false);
        }
    };

    const currentSubscription = subscriptions.length > 0 ? subscriptions[0] : null;
    const currentPlanId =
        typeof currentSubscription?.planId === 'object'
            ? currentSubscription?.planId?._id
            : currentSubscription?.planId;

    if (loading) {
        return (
            <div className="flex items-center justify-center min-h-screen">
                <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
            </div>
        );
    }

    const calculateDaysRemaining = (endDate: string) => {
        const end = new Date(endDate);
        const now = new Date();
        const diffTime = end.getTime() - now.getTime();
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        return diffDays > 0 ? diffDays : 0;
    };

    const getSubscriptionStatusLabel = (status?: string) => {
        switch ((status || '').toLowerCase()) {
            case 'active':
                return t('subscriptionPage.active');
            case 'pastdue':
                return t('subscriptionPage.pastDue');
            case 'cancelled':
                return t('subscriptionPage.cancelled');
            case 'expired':
                return t('subscriptionPage.expired');
            default:
                return status || t('subscriptionPage.unknownPlan');
        }
    };

    const getLocalizedPlanName = (period?: string, fallbackTitle?: string) => {
        const normalized = (period || '').trim().toLowerCase();

        if (
            normalized === 'annual' ||
            normalized === '12-month' ||
            normalized === 'yearly' ||
            normalized.includes('annual') ||
            normalized.includes('year') ||
            normalized.includes('12 month')
        ) return t('payment.periodAnnual');

        if (
            normalized === '6-month' ||
            normalized.includes('6 month') ||
            normalized.includes('semester')
        ) return t('payment.periodSixMonth');

        if (normalized === 'monthly' || normalized.includes('month')) return t('payment.periodMonthly');

        if (normalized === 'freely' || normalized.includes('trial') || normalized.includes('free')) {
            return t('payment.periodTrial');
        }

        return fallbackTitle || t('subscriptionPage.unknownPlan');
    };

    return (
        <div className="mx-auto max-w-7xl p-4 md:p-8">
            <div className="mb-10 text-center">
                <h1 className="text-3xl font-bold text-gray-900 mb-4">{t('subscriptionPage.title')}</h1>
                <p className="text-gray-600 max-w-2xl mx-auto">
                    {t('subscriptionPage.description')}
                </p>
            </div>

            {user?.userType !== 'admin' && currentSubscription && (
                <div className="mb-12 bg-linear-to-r from-blue-50 to-indigo-50 border border-blue-100 rounded-2xl p-6 md:p-8 flex flex-col md:flex-row items-center justify-between gap-6 shadow-sm">
                    <div>
                        <h2 className="text-xl font-bold text-gray-900 mb-2">{t('subscriptionPage.currentSubscription')}</h2>
                        <div className="flex items-center gap-3 mb-2">
                            <span className="bg-green-100 text-green-700 px-3 py-1 rounded-full text-sm font-medium flex items-center gap-1">
                                <Check className="w-3 h-3" /> {getSubscriptionStatusLabel(currentSubscription.status)}
                            </span>
                            <span className="text-gray-900 font-semibold text-lg">
                                {getLocalizedPlanName(
                                    typeof currentSubscription.planId === 'object'
                                        ? currentSubscription.planId?.period
                                        : undefined,
                                    typeof currentSubscription.planId === 'object'
                                        ? currentSubscription.planId?.title
                                        : undefined
                                )}
                            </span>
                        </div>
                        <p className="text-gray-600">
                            {t('subscriptionPage.expiresIn')} <span className="font-bold text-blue-600">{calculateDaysRemaining(currentSubscription.endDate)} {t('subscriptionPage.days')}</span> {t('subscriptionPage.on')} {new Date(currentSubscription.endDate).toLocaleDateString()}.
                        </p>
                    </div>
                    <div className="text-right hidden md:block">
                        <div className="text-sm text-gray-500 mb-1">{t('subscriptionPage.status')}</div>
                        <div className="text-lg font-medium text-gray-900 capitalize">{getSubscriptionStatusLabel(currentSubscription.status)}</div>
                    </div>
                </div>
            )}

            {user?.userType !== 'admin' && currentSubscription?.status?.toLowerCase() === 'active' && (
                <div className="mb-8 flex justify-end">
                    <Button variant="destructive" onClick={() => setCancelDialogOpen(true)}>
                        {t('subscriptionPage.cancelSubscription')}
                    </Button>
                </div>
            )}

            <Pricing
                ctaMode="upgrade"
                showTitleHighlight={false}
                compact
                currentPlanId={currentPlanId}
                disableActions={user?.userType === 'admin'}
            />

            {/* Admin: Full Plan Management */}
            {user?.userType === 'admin' && (
                <Card className="mt-10 bg-linear-to-r from-cyan-50 to-blue-50 border-cyan-100 rounded-2xl shadow-sm">
                    <CardHeader className="flex flex-row items-center justify-between">
                        <CardTitle>{t('adminPlans.title')}</CardTitle>
                        <Button onClick={() => setResetDialogOpen(true)} size="sm" className="gap-2" variant="outline">
                            <RotateCcw className="w-4 h-4" />
                            {resetPlansLabel}
                        </Button>
                    </CardHeader>
                    <CardContent className="space-y-4 p-0">
                        {planError && (
                            <p className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600 mx-6">{planError}</p>
                        )}
                        <div className="overflow-x-auto">
                            <Table>
                                <TableHeader>
                                    <TableRow className="bg-white/50">
                                        <TableHead className="w-[40%]">{t('adminPlans.colTitle')}</TableHead>
                                        <TableHead className="w-[15%]">{t('adminPlans.colPrice')}</TableHead>
                                        <TableHead className="w-[15%]">{t('adminPlans.colPeriod')}</TableHead>
                                        <TableHead className="w-[30%]">{t('common.actions')}</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {adminPlans.length === 0 ? (
                                        <TableRow>
                                            <TableCell colSpan={4} className="text-center py-10 text-muted-foreground">
                                                {t('adminPlans.noPlans')}
                                            </TableCell>
                                        </TableRow>
                                    ) : (
                                        adminPlans.map((plan) => (
                                            <TableRow key={plan._id} className="hover:bg-white/40">
                                                <TableCell className="font-medium">{getPlanTitleLabel(plan.title, t)}</TableCell>
                                                <TableCell>
                                                    {plan.price === 0 ? (
                                                        <span className="text-green-600 font-semibold">{t('adminPlans.free')}</span>
                                                    ) : (
                                                        <span>${plan.price}</span>
                                                    )}
                                                </TableCell>
                                                <TableCell>
                                                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-cyan-100 text-cyan-800">
                                                        {getPeriodLabel(plan.period, t)}
                                                    </span>
                                                </TableCell>
                                                <TableCell>
                                                    <div className="flex items-center gap-2">
                                                        <Button size="sm" variant="outline" onClick={() => openEditDialog(plan)}>
                                                            <Edit2 className="w-3.5 h-3.5 mr-1" />
                                                            {t('common.edit')}
                                                        </Button>
                                                    </div>
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    )}
                                </TableBody>
                            </Table>
                        </div>
                    </CardContent>
                </Card>
            )}

            <div className="mt-16 text-center bg-blue-50 rounded-2xl p-8 border border-blue-100">
                <div className="flex justify-center mb-4">
                    <ShieldCheck className="w-12 h-12 text-blue-600" />
                </div>
                <h3 className="text-xl font-bold text-gray-900 mb-2">{t('subscriptionPage.securityTitle')}</h3>
                <p className="text-gray-600 max-w-xl mx-auto">
                    {t('subscriptionPage.securityDescription')}
                </p>
            </div>

            {/* Create / Edit Plan Dialog */}
            <Dialog open={editDialogOpen} onOpenChange={(open) => !open && closeDialog()}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>
                            {`${t('adminPlans.editPlan')} — ${getPlanTitleLabel(editingPlan?.title, t)}`}
                        </DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4">
                        <div className="space-y-2">
                            <Label>{t('adminPlans.colPrice')}</Label>
                            <Input
                                type="number"
                                min="0"
                                step="0.01"
                                value={formPrice}
                                onChange={(e) => setFormPrice(e.target.value)}
                                placeholder="0.00"
                            />
                        </div>
                        {formError && (
                            <p className="text-sm text-red-600">{formError}</p>
                        )}
                    </div>
                    <DialogFooter>
                        <Button variant="outline" onClick={closeDialog} disabled={saving}>
                            {t('common.cancel')}
                        </Button>
                        <Button onClick={handleSavePlan} disabled={saving}>
                            {saving ? t('common.saving') : t('common.save')}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Reset Plans Confirmation */}
            <ConfirmDialog
                open={resetDialogOpen}
                onOpenChange={setResetDialogOpen}
                title={resetConfirmTitle}
                description={resetConfirmDescription}
                confirmLabel={resetPlansLabel}
                cancelLabel={t('common.cancel')}
                loading={resetting}
                onConfirm={handleResetPlans}
            />

            {/* Cancel Subscription Confirmation */}
            <ConfirmDialog
                open={cancelDialogOpen}
                onOpenChange={setCancelDialogOpen}
                title={t('subscriptionPage.cancelSubscription')}
                description={t('subscriptionPage.cancelSubscriptionDescription')}
                confirmLabel={t('subscriptionPage.cancelSubscription')}
                cancelLabel={t('common.cancel')}
                loading={cancelLoading}
                onConfirm={handleCancelSubscription}
            />
        </div>
    );
}
