
'use client';

import { Button } from '@/components/ui/button';
import { ArrowRight, Calendar, CheckCircle2, Loader2 } from 'lucide-react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { Suspense, useEffect, useState } from 'react';

import { useAuthStore } from '@/lib/auth-store';
import { useLanguage } from '@/lib/language-context';

function SuccessContent() {
    const searchParams = useSearchParams();
    const sessionId = searchParams.get('session_id');
    const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading');
    const [subscription, setSubscription] = useState<any>(null);
    const [errorMsg, setErrorMsg] = useState('');
    const router = useRouter();
    const { t } = useLanguage();
    const setHasActiveSubscription = useAuthStore((state) => state.setHasActiveSubscription);

    useEffect(() => {
        if (!sessionId) {
            setStatus('error');
            setErrorMsg(t('payment.noSessionId'));
            return;
        }

        const verifyPayment = async () => {
            try {
                const apiUrl = process.env.NEXT_PUBLIC_API_URL;
                const res = await fetch(`${apiUrl}/api/payments/verify/${sessionId}`);
                const data = await res.json();

                if (res.ok && data.success) {
                    setSubscription(data.subscription);
                    setStatus('success');
                    setHasActiveSubscription(true);
                } else {
                    setStatus('error');
                    setErrorMsg(data.error || t('payment.verificationFailedMessage'));
                }
            } catch (err) {
                console.error(err);
                setStatus('error');
                setErrorMsg(t('payment.serverConnectionFailed'));
            }
        };

        verifyPayment();
    }, [sessionId, setHasActiveSubscription, t]);

    // Loading State
    if (status === 'loading') {
        return (
            <div className="min-h-screen bg-linear-to-br from-cyan-400 via-cyan-500 to-blue-600 flex items-center justify-center">
                <div className="backdrop-blur-sm bg-white/95 rounded-2xl shadow-2xl p-8 flex flex-col items-center animate-in fade-in zoom-in-95 duration-300">
                    <Loader2 className="h-10 w-10 animate-spin text-cyan-600 mb-4" />
                    <h2 className="text-xl font-bold text-gray-900">{t('payment.verifyingPayment')}</h2>
                </div>
            </div>
        );
    }

    // Error State
    if (status === 'error') {
        return (
            <div className="min-h-screen bg-linear-to-br from-cyan-400 via-cyan-500 to-blue-600 flex items-center justify-center p-4">
                <div className="backdrop-blur-sm bg-white/95 rounded-2xl shadow-2xl p-8 max-w-md w-full text-center animate-in fade-in slide-in-from-bottom-4">
                    <div className="flex justify-center mb-6">
                        <div className="bg-red-100 p-4 rounded-full">
                            <span className="text-4xl">⚠️</span>
                        </div>
                    </div>
                    <h1 className="text-2xl font-bold text-gray-900 mb-2">{t('payment.verificationFailed')}</h1>
                    <p className="text-gray-600 mb-8">{errorMsg}</p>
                    <div className="space-y-3">
                        <Button
                            onClick={() => router.push('/dashboard')}
                            className="w-full h-12 bg-gray-900 hover:bg-gray-800 text-white font-semibold rounded-lg transition-all duration-300"
                        >
                            {t('payment.goToDashboard')}
                        </Button>
                        <Button
                            variant="ghost"
                            onClick={() => router.push('/')}
                            className="w-full text-gray-600 hover:text-gray-900"
                        >
                            {t('payment.backToHome')}
                        </Button>
                    </div>
                </div>
            </div>
        );
    }

    // Success State Data
    const user = subscription?.userId;

    let displayName = t('payment.valuedCustomer');
    if (user && typeof user === 'object' && user.firstName) {
        displayName = `${user.firstName} ${user.lastName}`;
    }

    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');
    };

    const localizedPlanName = getLocalizedPlanName(subscription?.planId?.period, subscription?.planId?.title);

    const expiryDate = subscription?.endDate
        ? new Date(subscription.endDate).toLocaleDateString(undefined, {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        })
        : t('subscriptionPage.unknownPlan');

    const handleDashboardRedirect = () => {
        // Future: You can use userType to redirect to different dashboards
        // e.g. if (userType === 'patient') router.push('/patient/dashboard');
        router.push('/dashboard');
    };

    return (
        <div className="min-h-screen bg-linear-to-br from-cyan-400 via-cyan-500 to-blue-600 overflow-hidden flex items-center justify-center relative py-8 px-4">
            {/* Decorative circles (reused from Register page) */}
            <div className="absolute bottom-0 right-0 w-96 h-96 bg-yellow-300 rounded-full opacity-20 transform translate-x-32 translate-y-32 animate-pulse"></div>
            <div className="absolute top-0 left-0 w-72 h-72 bg-white rounded-full opacity-5 animate-pulse" style={{ animationDelay: '0.5s' }}></div>

            <div className="relative z-10 w-full max-w-lg">
                <div className="backdrop-blur-sm bg-white/95 rounded-2xl shadow-2xl p-8 transform transition-all duration-500 hover:shadow-3xl animate-in fade-in slide-in-from-bottom-4">

                    {/* Header */}
                    <div className="text-center mb-8 animate-in fade-in duration-500" style={{ animationDelay: '0.1s' }}>
                        <div className="flex justify-center mb-6">
                            <div className="relative w-24 h-24 flex items-center justify-center bg-green-100 rounded-full">
                                <CheckCircle2 className="w-12 h-12 text-green-600" />
                            </div>
                        </div>
                        <h1 className="text-3xl font-bold bg-linear-to-r from-cyan-600 to-blue-600 bg-clip-text text-transparent mb-2">
                            {t('payment.paymentSuccessTitle')}
                        </h1>
                        <p className="text-gray-600">{t('payment.paymentSuccessSubtitle')}</p>
                    </div>

                    {/* Content Card */}
                    <div className="bg-gray-50 rounded-xl p-6 mb-8 border border-gray-100 animate-in fade-in duration-500" style={{ animationDelay: '0.2s' }}>
                        <div className="flex justify-between items-center mb-4 border-b border-gray-200 pb-4">
                            <span className="text-sm font-semibold text-gray-500 uppercase tracking-wide">{t('payment.subscriber')}</span>
                            <span className="text-lg font-bold text-gray-900">{displayName}</span>
                        </div>

                        <div className="flex justify-between items-center mb-4 border-b border-gray-200 pb-4">
                            <span className="text-sm font-semibold text-gray-500 uppercase tracking-wide">{t('payment.selectedPlan')}</span>
                            <span className="text-lg font-bold text-cyan-700">{localizedPlanName}</span>
                        </div>

                        <div className="flex justify-between items-center">
                            <div className="flex items-center text-gray-600 font-medium">
                                <Calendar className="h-5 w-5 mr-2 text-cyan-600" />
                                <span>{t('payment.expiresOn')}</span>
                            </div>
                            <span className="text-lg font-bold text-cyan-700 bg-cyan-50 px-3 py-1 rounded-lg border border-cyan-100">
                                {expiryDate}
                            </span>
                        </div>
                    </div>

                    {/* Actions */}
                    <div className="space-y-4 animate-in fade-in duration-500" style={{ animationDelay: '0.3s' }}>
                        <Button
                            onClick={handleDashboardRedirect}
                            className="w-full min-h-16 bg-linear-to-r from-cyan-500 to-blue-600 hover:from-cyan-600 hover:to-blue-700 text-white font-semibold py-5 px-4 rounded-lg transition-all duration-300 transform hover:shadow-lg active:scale-95 text-lg"
                        >
                            <span className="flex items-center justify-center gap-2">
                                {t('payment.goToDashboard')}
                                <ArrowRight className="w-5 h-5" />
                            </span>
                        </Button>

                        <div className="text-center">
                            <Link
                                href="/"
                                className="text-gray-500 hover:text-gray-900 font-medium text-sm transition-colors duration-200 inline-flex items-center gap-1"
                            >
                                {t('payment.backToHome')}
                            </Link>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    );
}

export default function PaymentSuccessPage() {
    return (
        <Suspense fallback={<div className="min-h-screen flex items-center justify-center" />}>
            <SuccessContent />
        </Suspense>
    );
}
