
'use client';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { useAuthStore } from '@/lib/auth-store';
import { useLanguage } from '@/lib/language-context';
import { Check, ShieldCheck, User as UserIcon, CreditCard, ArrowRight } from 'lucide-react';
import { useSearchParams, useRouter } from 'next/navigation';
import { Suspense, useEffect, useState } from 'react';
import Image from 'next/image';

function SummaryContent() {
    const searchParams = useSearchParams();
    const router = useRouter();
    const { user, token } = useAuthStore();
    const { t } = useLanguage();
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');

    // Retrieve data from URL params
    const planName = searchParams.get('planName');
    const planPrice = searchParams.get('planPrice');
    const planId = searchParams.get('planId');
    const planPeriod = searchParams.get('period');

    const getLocalizedPlanName = (period?: string | null, fallbackName?: string | null) => {
        const normalizedPeriod = (period || '').trim().toLowerCase();
        const normalizedName = (fallbackName || '').trim().toLowerCase();

        if (
            normalizedPeriod === 'annual' ||
            normalizedPeriod === '12-month' ||
            normalizedPeriod === 'yearly' ||
            normalizedName.includes('annual') ||
            normalizedName.includes('year') ||
            normalizedName.includes('12 month')
        ) {
            return t('home.pricing.annual.name');
        }

        if (
            normalizedPeriod === '6-month' ||
            normalizedName.includes('6 month') ||
            normalizedName.includes('semester')
        ) {
            return t('home.pricing.sixMonth.name');
        }

        if (normalizedPeriod === 'monthly' || normalizedName.includes('month')) {
            return t('home.pricing.monthly.name');
        }

        if (
            normalizedPeriod === 'freely' ||
            normalizedName.includes('trial') ||
            normalizedName.includes('free')
        ) {
            return t('home.pricing.freeTrial.name');
        }

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

    const localizedPlanName = getLocalizedPlanName(planPeriod, planName);

    const getLocalizedBillingPeriod = (period?: string | null) => {
        const normalized = (period || '').trim().toLowerCase();

        if (!normalized) return t('payment.oneTime');

        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 localizedPlanName || t('payment.oneTime');
    };

    const getSelectedPlanLabel = (period?: string | null, fallbackName?: string | null) => {
        const normalized = (period || '').trim().toLowerCase();
        if (!normalized && !fallbackName) return t('subscriptionPage.unknownPlan');

        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 fallbackName || t('subscriptionPage.unknownPlan');
    };

    // If user is not logged in, redirect to login
    useEffect(() => {
        if (!user || !token) {
            router.push(`/login?redirect=/payment/summary?planName=${planName}&planPrice=${planPrice}&period=${planPeriod}`);
        }
    }, [user, token, router, planName, planPrice, planPeriod]);

    // Parse price to number
    const numericPrice = planPrice ? parseFloat(planPrice.replace(/[^0-9.]/g, '')) : 0;

    const handleCheckout = async () => {
        setIsLoading(true);
        setError('');

        try {
            const payload = {
                userId: user?.id,
                planId: planId,
                currency: 'USD',
                metadata: {
                    productName: localizedPlanName,
                    amount: numericPrice,
                    planPeriod: planPeriod,
                    email: user?.email,
                }
            };

            const apiUrl = process.env.NEXT_PUBLIC_API_URL;
            const response = await fetch(`${apiUrl}/api/payments/checkout`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(payload)
            });

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.error || t('payment.checkoutFailed'));
            }

            const checkoutUrl = data.data?.url || data.url;
            if (checkoutUrl) {
                window.location.href = checkoutUrl;
            } else {
                throw new Error(t('payment.noCheckoutUrl'));
            }

        } catch (err: any) {
            console.error(err);
            setError(err.message || t('payment.somethingWentWrong'));
        } finally {
            setIsLoading(false);
        }
    };

    if (!user) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-gray-50">
                <div className="flex flex-col items-center">
                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-cyan-600 mb-4"></div>
                    <p className="text-gray-600">{t('payment.redirectingToLogin')}</p>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-linear-to-br from-cyan-400 via-cyan-500 to-blue-600 flex items-center justify-center relative py-12 px-4 sm:px-6 lg:px-8 overflow-hidden">
            {/* Decorative circles */}
            <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="max-w-4xl w-full relative z-10">
                <div className="backdrop-blur-sm bg-white/95 rounded-2xl shadow-2xl p-8 transform transition-all duration-500">

                    <div className="text-center mb-8">
                        <div className="inline-flex items-center justify-center p-3 bg-cyan-100 rounded-full mb-4">
                            <CreditCard className="h-8 w-8 text-cyan-600" />
                        </div>
                        <h1 className="text-3xl font-bold text-gray-900">{t('payment.orderSummary')}</h1>
                        <p className="mt-2 text-gray-600">{t('payment.reviewSubscription')}</p>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                        {/* User Details Card */}
                        <div className="bg-gray-50 rounded-xl p-6 border border-gray-100 hover:shadow-md transition-shadow">
                            <h3 className="flex items-center text-lg font-semibold text-gray-900 mb-6">
                                <UserIcon className="w-5 h-5 mr-3 text-cyan-600" />
                                {t('payment.accountInformation')}
                            </h3>
                            <div className="space-y-4">
                                <div className="flex justify-between border-b border-gray-200 pb-2">
                                    <span className="text-sm text-gray-500">{t('payment.fullName')}</span>
                                    <span className="text-sm font-medium text-gray-900">{user.firstName} {user.lastName}</span>
                                </div>
                                <div className="flex justify-between border-b border-gray-200 pb-2">
                                    <span className="text-sm text-gray-500">{t('common.email')}</span>
                                    <span className="text-sm font-medium text-gray-900 truncate ml-4" title={user.email}>{user.email}</span>
                                </div>
                                <div className="flex justify-between items-center pt-1">
                                    <span className="text-sm text-gray-500">{t('payment.userType')}</span>
                                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 capitalize">
                                        {user.userType}
                                    </span>
                                </div>
                            </div>
                        </div>

                        {/* Plan Details Card */}
                        <div className="bg-gradient-to-br from-slate-800 to-slate-900 rounded-xl p-6 text-white shadow-lg flex flex-col justify-between relative overflow-hidden">
                            {/* Abstract bg pattern */}
                            <div className="absolute top-0 right-0 w-32 h-32 bg-white opacity-5 rounded-bl-full transform translate-x-10 -translate-y-10"></div>

                            <div>
                                <h3 className="flex items-center text-lg font-semibold text-white mb-6">
                                    <ShieldCheck className="w-5 h-5 mr-3 text-cyan-400" />
                                    {t('payment.subscriptionPlan')}
                                </h3>

                                <div className="space-y-4">
                                    <div className="flex justify-between items-center">
                                        <span className="text-slate-300">{t('payment.selectedPlan')}</span>
                                        <span className="text-xl font-bold text-cyan-400">
                                            {getSelectedPlanLabel(planPeriod, planName)}
                                        </span>
                                    </div>
                                    <div className="flex justify-between items-center">
                                        <span className="text-slate-300">{t('payment.billingPeriod')}</span>
                                        <span className="bg-slate-700 px-2 py-1 rounded text-xs">{getLocalizedBillingPeriod(planPeriod)}</span>
                                    </div>

                                    <div className="my-6 border-t border-slate-700"></div>

                                    <div className="flex justify-between items-end">
                                        <span className="text-slate-300 mb-1">{t('payment.totalToPay')}</span>
                                        <span className="text-4xl font-bold text-white">${numericPrice}</span>
                                    </div>
                                </div>
                            </div>

                            <div className="mt-8">
                                {error && (
                                    <div className="bg-red-500/10 border border-red-500/50 rounded-lg p-3 mb-4">
                                        <p className="text-sm text-red-200 text-center">{error}</p>
                                    </div>
                                )}
                                <Button
                                    className="w-full bg-cyan-500 hover:bg-cyan-400 text-white font-bold py-6 text-lg shadow-lg shadow-cyan-900/20 transition-all hover:scale-[1.02] active:scale-95"
                                    onClick={handleCheckout}
                                    disabled={isLoading}
                                >
                                    {isLoading ? (
                                        <span className="flex items-center gap-2">
                                            <svg className="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                            </svg>
                                            {t('payment.processing')}
                                        </span>
                                    ) : (
                                        <span className="flex items-center justify-center">
                                            {t('payment.proceedToPayment')} <ArrowRight className="ml-2 w-5 h-5" />
                                        </span>
                                    )}
                                </Button>
                            </div>
                        </div>
                    </div>

                    <div className="mt-6 text-center">
                        <p className="text-xs text-gray-500 flex items-center justify-center gap-1">
                            <ShieldCheck className="w-3 h-3" /> {t('payment.securePayment')}
                        </p>
                    </div>
                </div>
            </div>
        </div>
    );
}

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