'use client';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { useLanguage } from '@/lib/language-context';
import { usePlansStore } from '@/lib/plans-store';
import { Check } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';

interface PricingProps {
    ctaMode?: 'subscribe' | 'upgrade';
    showTitleHighlight?: boolean;
    compact?: boolean;
    currentPlanId?: string;
    disableActions?: boolean;
}

interface DisplayPlan {
    id: string;
    name: string;
    duration: string;
    description: string;
    buttonText: string;
    features: string[];
    highlight: boolean;
    recommended: boolean;
    price: string;
    rawPrice: number;
    periodKey: string;
    isCurrentPlan: boolean;
    isLowerTier: boolean;
}

export default function Pricing({
    ctaMode = 'subscribe',
    showTitleHighlight = true,
    compact = false,
    currentPlanId,
    disableActions = false,
}: PricingProps) {
    const router = useRouter();
    const { t } = useLanguage();
    const dbPlans = usePlansStore((state) => state.plans);
    const isLoading = usePlansStore((state) => state.isLoading);
    const error = usePlansStore((state) => state.error);
    const fetchPlans = usePlansStore((state) => state.fetchPlans);
    const sectionSpacingClass = compact ? 'py-0 sm:py-0' : 'py-24 sm:py-32';
    const plansTopSpacingClass = showTitleHighlight ? 'mt-16 sm:mt-20' : 'mt-8 sm:mt-10';
    const plansGridClass = compact
        ? 'grid max-w-md grid-cols-1 gap-6 md:max-w-2xl md:grid-cols-1 lg:max-w-4xl lg:grid-cols-2 2xl:max-w-none 2xl:grid-cols-4'
        : 'grid max-w-md grid-cols-1 gap-6 md:max-w-3xl md:grid-cols-2 xl:max-w-none xl:grid-cols-4';

    // Fetch plans if not already loaded
    useEffect(() => {
        if (dbPlans.length === 0 && !isLoading) {
            fetchPlans();
        }
    }, [dbPlans.length, isLoading, fetchPlans]);

    // Configuration for UI presentation based on plan period
    const getPlanConfig = (period: string) => {
        switch (period) {
            case 'freely':
                return {
                    name: t('home.pricing.freeTrial.name'),
                    duration: t('home.pricing.freeTrial.duration'),
                    description: t('home.pricing.freeTrial.description'),
                    buttonText: t('home.pricing.freeTrial.buttonText'),
                    features: [
                        t('home.pricing.features.scheduling'),
                        t('home.pricing.features.confirmations'),
                        t('home.pricing.features.history'),
                        t('home.pricing.features.odontogram'),
                        t('home.pricing.features.support'),
                        t('home.pricing.features.patients'),
                        t('home.pricing.features.prescriptions'),
                        t('home.pricing.features.signature'),
                        t('home.pricing.features.pdf'),
                    ],
                    highlight: false,
                    recommended: false
                };
            case 'monthly':
                return {
                    name: t('home.pricing.monthly.name'),
                    duration: t('home.pricing.monthly.duration'),
                    description: '',
                    buttonText: t('home.pricing.monthly.buttonText'),
                    features: [
                        t('home.pricing.features.scheduling'),
                        t('home.pricing.features.confirmations'),
                        t('home.pricing.features.history'),
                        t('home.pricing.features.odontogram'),
                        t('home.pricing.features.support'),
                        t('home.pricing.features.patients'),
                        t('home.pricing.features.prescriptions'),
                        t('home.pricing.features.signature'),
                        t('home.pricing.features.pdf'),
                    ],
                    highlight: false,
                    recommended: false
                };
            case '6-month':
                return {
                    name: t('home.pricing.sixMonth.name'),
                    duration: t('home.pricing.sixMonth.duration'),
                    description: '',
                    buttonText: t('home.pricing.sixMonth.buttonText'),
                    features: [
                        t('home.pricing.features.scheduling'),
                        t('home.pricing.features.confirmations'),
                        t('home.pricing.features.history'),
                        t('home.pricing.features.odontogram'),
                        t('home.pricing.features.support'),
                        t('home.pricing.features.patients'),
                        t('home.pricing.features.prescriptions'),
                        t('home.pricing.features.signature'),
                        t('home.pricing.features.pdf'),
                        t('home.pricing.features.doctorLimit2'),
                    ],
                    highlight: false,
                    recommended: false
                };
            case 'annual':
                return {
                    name: t('home.pricing.annual.name'),
                    duration: t('home.pricing.annual.duration'),
                    description: t('home.pricing.annual.description'),
                    buttonText: t('home.pricing.annual.buttonText'),
                    features: [
                        t('home.pricing.features.scheduling'),
                        t('home.pricing.features.confirmations'),
                        t('home.pricing.features.history'),
                        t('home.pricing.features.odontogram'),
                        t('home.pricing.features.support'),
                        t('home.pricing.features.patients'),
                        t('home.pricing.features.prescriptions'),
                        t('home.pricing.features.signature'),
                        t('home.pricing.features.pdf'),
                        t('home.pricing.features.doctorLimit5'),
                    ],
                    highlight: true,
                    recommended: true
                };
            default:
                return null;
        }
    };

    // Find the current plan's price for tier comparison
    const currentPlanPrice = currentPlanId
        ? dbPlans.find((p) => p._id === currentPlanId)?.price ?? -1
        : -1;

    // Prepare plans for rendering: match DB plans with UI config
    const displayPlans: DisplayPlan[] = dbPlans
        .map((plan) => {
            const isFreeForeverPlan = plan.period === 'freely' && plan.title.toLowerCase().includes('forever');
            // Free Forever is admin-assigned; do not show it in public pricing cards.
            if (isFreeForeverPlan) return null;

            const config = getPlanConfig(plan.period);
            if (!config) return null;
            const isCurrentPlan = !!currentPlanId && currentPlanId === plan._id;
            // A plan is a lower tier if its price is less than the current plan's price
            const isLowerTier = !!currentPlanId && !isCurrentPlan && plan.price <= currentPlanPrice;

            const buttonText =
                ctaMode === 'upgrade' && plan.price > 0
                    ? `${t('subscriptionPage.upgradeTo')} ${config.name}`
                    : config.buttonText;

            return {
                ...config,
                buttonText,
                id: plan._id,
                price: plan.price === 0 ? t('home.pricing.freeTrial.price') : `$${plan.price}`,
                rawPrice: plan.price,
                periodKey: plan.period,
                isCurrentPlan,
                isLowerTier,
            };
        })
        .filter((plan): plan is DisplayPlan => plan !== null)
        .sort((a, b) => a.rawPrice - b.rawPrice); // Sort by price

    if (isLoading) {
        return (
            <div id="pricing" className={`bg-gray-50 ${sectionSpacingClass} flex justify-center items-center`}>
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-cyan-600"></div>
            </div>
        );
    }

    if (error) {
        return (
            <div id="pricing" className={`bg-gray-50 ${sectionSpacingClass} flex justify-center items-center`}>
                <p className="text-red-600">{t('subscriptionPage.errorLoadingPlans')}</p>
            </div>
        );
    }

    return (
        <div id="pricing" className={`bg-gray-50 ${sectionSpacingClass}`}>
            <div className="mx-auto max-w-7xl px-6 lg:px-8">
                <div className="mx-auto max-w-4xl text-center">
                    <h2 className="text-base font-semibold leading-7 text-cyan-600">{t('home.pricing.title')}</h2>
                    {showTitleHighlight && (
                        <p className="mt-2 text-4xl font-bold tracking-tight text-gray-900 sm:text-5xl">
                            {t('home.pricing.titleHighlight')}
                        </p>
                    )}
                </div>
                <div className={`isolate mx-auto ${plansTopSpacingClass} ${plansGridClass} xl:mx-0`}>
                    {displayPlans.length > 0 ? (
                        displayPlans.map((plan) => (
                            <Card
                                key={plan.id}
                                className={`relative flex h-full min-w-0 flex-col justify-between p-2 shadow-lg ring-1 transition-all duration-200 md:hover:-translate-y-1 ${plan.highlight
                                    ? 'bg-white ring-cyan-600 shadow-xl z-10'
                                    : 'bg-white ring-gray-200'
                                    }`}
                            >
                                <CardHeader>
                                    <div className="mb-2 flex min-h-7 items-center">
                                        {plan.isCurrentPlan && (
                                            <span className="inline-flex rounded-full bg-blue-600 px-3 py-1 text-[10px] font-bold uppercase tracking-wider text-white md:text-xs">
                                                {t('subscriptionPage.currentPlanBadge')}
                                            </span>
                                        )}
                                    </div>
                                    <div className="flex flex-wrap items-start gap-3">
                                        <h3
                                            className={`min-w-0 flex-1 text-lg font-semibold leading-8 ${plan.highlight ? 'text-cyan-600' : 'text-gray-900'
                                                }`}
                                        >
                                            {plan.name}
                                        </h3>
                                        {plan.recommended && (
                                            <span className="inline-flex whitespace-nowrap rounded-full bg-cyan-600/10 px-2.5 py-1 text-xs font-semibold leading-5 text-cyan-600">
                                                {t('home.pricing.annual.recommendedBadge')}
                                            </span>
                                        )}
                                    </div>
                                    <CardTitle className="mt-4 flex flex-wrap items-baseline gap-x-2 gap-y-1">
                                        <span className="break-words text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl">{plan.price}</span>
                                        {plan.duration && (
                                            <span className="text-sm font-semibold leading-6 text-gray-600">{plan.duration}</span>
                                        )}
                                    </CardTitle>
                                    <CardDescription className="mt-2 text-sm leading-6 text-gray-600">
                                        {plan.description}
                                    </CardDescription>
                                </CardHeader>
                                <CardContent>
                                    <ul role="list" className="mt-2 mb-6 space-y-3 text-sm leading-6 text-gray-600">
                                        {plan.features.map((feature: string, idx: number) => (
                                            <li key={idx} className="flex gap-x-3">
                                                <Check className="h-6 w-5 flex-none text-cyan-600" aria-hidden="true" />
                                                {feature}
                                            </li>
                                        ))}
                                    </ul>
                                </CardContent>
                                <CardFooter>
                                    {plan.isCurrentPlan ? (
                                        <Button
                                            disabled
                                            className="nav-btn w-full mb-4 h-auto py-2 whitespace-normal break-words text-center bg-green-50 text-green-700 cursor-default hover:bg-green-50"
                                        >
                                            {t('subscriptionPage.currentPlanButton')}
                                        </Button>
                                    ) : plan.isLowerTier ? (
                                        <Button
                                            disabled
                                            className="nav-btn w-full mb-4 h-auto py-2 whitespace-normal break-words text-center bg-gray-100 text-gray-400 cursor-not-allowed hover:bg-gray-100"
                                        >
                                            {plan.buttonText}
                                        </Button>
                                    ) : plan.rawPrice > 0 ? (
                                        <Button
                                            disabled={disableActions}
                                            onClick={() => {
                                                if (disableActions) return;
                                                const params = new URLSearchParams({
                                                    planName: plan.name,
                                                    planPrice: plan.rawPrice.toString(),
                                                    period: plan.periodKey,
                                                    planId: plan.id,
                                                }).toString();
                                                router.push(`/payment/summary?${params}`);
                                            }}
                                            className={`nav-btn w-full mb-4 h-auto py-2 whitespace-normal break-words text-center ${plan.highlight
                                                ? (disableActions ? 'bg-gray-100 text-gray-400 cursor-not-allowed hover:bg-gray-100' : 'bg-cyan-600 text-white hover:bg-cyan-500')
                                                : (disableActions ? 'bg-gray-100 text-gray-400 cursor-not-allowed hover:bg-gray-100' : 'bg-cyan-50 text-cyan-600 hover:bg-cyan-100')
                                                }`}
                                        >
                                            {plan.buttonText}
                                        </Button>
                                    ) : plan.periodKey === 'freely' ? (
                                        <Button
                                            disabled
                                            className="nav-btn w-full mb-4 h-auto py-2 whitespace-normal break-words text-center bg-gray-100 text-gray-400 cursor-not-allowed hover:bg-gray-100"
                                        >
                                            {plan.buttonText}
                                        </Button>
                                    ) : (
                                        <Button
                                            disabled
                                            className="nav-btn w-full mb-4 h-auto py-2 whitespace-normal break-words text-center bg-gray-100 text-gray-400 cursor-default hover:bg-gray-100"
                                        >
                                            {t('subscriptionPage.freeForever')}
                                        </Button>
                                    )}
                                </CardFooter>
                            </Card>
                        ))
                    ) : (
                        <div className="col-span-4 text-center text-gray-500">
                            {t('common.loading')}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
