'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { useAuthStore, UserPlan } from '@/store/authStore';
import { paddleInstance, setPaddleCheckoutHandlers } from '@/app/PaddleProvider';

type BillingCycle = 'monthly' | 'yearly';

interface PlanConfig {
  id: UserPlan;
  name: string;
  subtitle: string;
  monthlyPrice: number | null;
  yearlyMonthlyPrice: number | null;
  yearlyTotal: number | null;
  badge?: string;
  cta: string;
  features: Array<{ text: string; included: boolean }>;
}

function CheckIcon({ included }: { included: boolean }) {
  if (included) {
    return (
      <svg className="w-4 h-4 text-brand-purple flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
      </svg>
    );
  }
  return (
    <svg className="w-4 h-4 text-red-400 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
    </svg>
  );
}

export default function PricingSection() {
  const t = useTranslations('pricing');
  const { isAuthenticated, user, createCheckout, verifyTransaction, updateSubscription } = useAuthStore();
  const router = useRouter();
  const [billing, setBilling] = useState<BillingCycle>('monthly');
  const [loading, setLoading] = useState<UserPlan | null>(null);
  const [checkoutError, setCheckoutError] = useState<string | null>(null);

  const PLANS: PlanConfig[] = [
    {
      id: 'free',
      name: t('plans.free.name'),
      subtitle: t('plans.free.subtitle'),
      monthlyPrice: 0,
      yearlyMonthlyPrice: 0,
      yearlyTotal: 0,
      cta: t('plans.free.cta'),
      features: [
        { text: t('features.unlimitedListings'), included: true },
        { text: t('features.seeGap'), included: true },
        { text: t('features.countryRevealed'), included: false },
        { text: t('features.manualExplorer'), included: false },
        { text: t('features.priceAlerts'), included: false },
        { text: t('features.historicalData'), included: false },
      ],
    },
    {
      id: 'basic',
      name: t('plans.basic.name'),
      subtitle: t('plans.basic.subtitle'),
      monthlyPrice: 4.99,
      yearlyMonthlyPrice: 3.99,
      yearlyTotal: 48,
      cta: t('plans.basic.cta'),
      features: [
        { text: t('features.searches5'), included: true },
        { text: t('features.countryRevealed'), included: true },
        { text: t('features.cheapestPrice'), included: true },
        { text: t('features.manualExplorer'), included: false },
        { text: t('features.priceAlerts'), included: false },
        { text: t('features.historicalData'), included: false },
      ],
    },
    {
      id: 'premium',
      name: t('plans.premium.name'),
      subtitle: t('plans.premium.subtitle'),
      monthlyPrice: 9.99,
      yearlyMonthlyPrice: 7.99,
      yearlyTotal: 96,
      badge: t('mostPopular'),
      cta: t('plans.premium.cta'),
      features: [
        { text: t('features.searches20'), included: true },
        { text: t('features.countryRevealed'), included: true },
        { text: t('features.manualExplorer'), included: true },
        { text: t('features.priceAlertsUp5'), included: true },
        { text: t('features.historicalData'), included: true },
        { text: t('features.unlimitedAlertsShort'), included: false },
      ],
    },
    {
      id: 'max',
      name: t('plans.max.name'),
      subtitle: t('plans.max.subtitle'),
      monthlyPrice: 19,
      yearlyMonthlyPrice: 15.20,
      yearlyTotal: 182,
      cta: t('plans.max.cta'),
      features: [
        { text: t('features.searches100'), included: true },
        { text: t('features.countryRevealed'), included: true },
        { text: t('features.manualExplorer'), included: true },
        { text: t('features.unlimitedAlerts'), included: true },
        { text: t('features.historicalData'), included: true },
        { text: t('features.priorityAccess'), included: true },
      ],
    },
  ];

  async function handleSelectPlan(plan: UserPlan) {
    if (plan === 'free') {
      router.push('/');
      return;
    }
    if (!isAuthenticated) {
      router.push(`/signin?plan=${plan}&billing=${billing}`);
      return;
    }
    if (user?.plan === plan && (user?.planBillingCycle ?? 'monthly') === billing) return;

    setLoading(plan);
    setCheckoutError(null);

    const hasPaidSubscription = user?.plan !== 'free';

    if (hasPaidSubscription) {
      try {
        await updateSubscription(plan, billing);
        router.push('/billing');
      } catch {
        setCheckoutError(t('errors.updateFailed'));
        setLoading(null);
      }
      return;
    }

    if (!paddleInstance) {
      setCheckoutError(t('errors.paymentUnavailable'));
      setLoading(null);
      return;
    }

    try {
      const priceId = await createCheckout(plan, billing);

      setPaddleCheckoutHandlers({
        onCompleted: async (transactionId) => {
          try {
            await verifyTransaction(transactionId);
            router.push('/');
          } catch {
            setCheckoutError(t('errors.activationFailed'));
            setLoading(null);
          }
        },
        onClosed: () => setLoading(null),
      });

      paddleInstance.Checkout.open({
        items: [{ priceId, quantity: 1 }],
        ...(user?.email ? { customer: { email: user.email } } : {}),
        customData: { userId: user?.email ?? '' },
        settings: { displayMode: 'overlay', theme: 'light' },
      });
    } catch {
      setCheckoutError(t('errors.checkoutFailed'));
      setLoading(null);
    }
  }

  return (
    <section id="pricing-section" className="bg-gray-50 py-16">
      <div className="max-w-6xl mx-auto px-4 sm:px-6">
        <h2 className="text-2xl font-bold text-brand-purple text-center mb-4">{t('heading')}</h2>
        <p className="text-center text-gray-500 text-sm mb-8">{t('subheading')}</p>

        {/* Billing toggle */}
        <div className="flex items-center justify-center gap-2 mb-8">
          <button
            onClick={() => setBilling('monthly')}
            className={`px-5 py-2 rounded-full text-sm font-medium border transition-colors ${
              billing === 'monthly'
                ? 'bg-white border-gray-300 text-gray-900 shadow-sm'
                : 'border-transparent text-gray-500 hover:text-gray-700'
            }`}
          >
            {t('billingMonthly')}
          </button>
          <button
            onClick={() => setBilling('yearly')}
            className={`px-5 py-2 rounded-full text-sm font-medium border transition-colors flex items-center gap-2 ${
              billing === 'yearly'
                ? 'bg-white border-gray-300 text-gray-900 shadow-sm'
                : 'border-transparent text-gray-500 hover:text-gray-700'
            }`}
          >
            {t('billingYearly')}
            <span className="bg-green-100 text-green-700 text-xs font-semibold px-1.5 py-0.5 rounded">{t('yearlySavingsBadge')}</span>
          </button>
        </div>

        {/* Checkout error */}
        {checkoutError && (
          <div className="mb-6 px-4 py-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700 text-center">
            {checkoutError}
          </div>
        )}

        {/* Plan cards */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
          {PLANS.map((plan) => {
            const price = billing === 'yearly' ? plan.yearlyMonthlyPrice : plan.monthlyPrice;
            const userCycle = user?.planBillingCycle ?? 'monthly';
            const isCurrentPlan = isAuthenticated && user?.plan === plan.id && userCycle === billing;
            const isSamePlanDifferentCycle = isAuthenticated && user?.plan === plan.id && userCycle !== billing && plan.id !== 'free';
            const isPremium = plan.id === 'premium';

            const ctaLabel = isSamePlanDifferentCycle
              ? (billing === 'monthly' ? t('switchToMonthly') : t('switchToYearly'))
              : plan.cta;

            return (
              <div
                key={plan.id}
                className={`relative bg-white rounded-2xl p-6 flex flex-col border-2 transition-shadow ${
                  isPremium ? 'border-brand-purple shadow-lg' : 'border-gray-100 shadow-sm'
                }`}
              >
                {plan.badge && (
                  <div className="absolute top-0 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-purple-50 text-brand-purple text-xs font-semibold px-3 py-1 rounded-full whitespace-nowrap border border-purple-200">
                    {plan.badge}
                  </div>
                )}

                <p className="text-[11px] font-semibold text-gray-400 uppercase tracking-widest mb-1">{plan.id === 'free' ? 'FREE' : plan.id.toUpperCase()}</p>
                <h3 className="text-3xl font-bold text-gray-900 mb-1">
                  {price === 0 ? 'Free' : `€${price?.toFixed(2)}`}
                  {price !== 0 && <span className="text-base font-normal text-gray-400">/mo</span>}
                </h3>
                {billing === 'yearly' && plan.yearlyTotal !== null && plan.yearlyTotal > 0 && (
                  <p className="text-xs text-gray-400 mb-1">€{plan.yearlyTotal} billed yearly</p>
                )}
                <p className="text-xs text-gray-400 mb-5">{plan.subtitle}</p>

                <button
                  onClick={() => handleSelectPlan(plan.id)}
                  disabled={isCurrentPlan || loading !== null}
                  className={`w-full py-2.5 rounded-lg text-sm font-medium transition-colors mb-5 flex items-center justify-center gap-1.5 ${
                    isCurrentPlan
                      ? 'bg-gray-100 text-gray-400 cursor-default'
                      : isSamePlanDifferentCycle
                      ? 'bg-white border border-brand-purple text-brand-purple hover:bg-purple-50'
                      : isPremium
                      ? 'bg-brand-purple hover:bg-purple-700 text-white'
                      : 'bg-white border border-gray-300 hover:border-gray-400 text-gray-800'
                  }`}
                >
                  {loading === plan.id ? (
                    <span className="inline-block w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin" />
                  ) : isCurrentPlan ? (
                    t('currentPlan')
                  ) : (
                    <>
                      {ctaLabel}
                      <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M14 5l7 7m0 0l-7 7m7-7H3" />
                      </svg>
                    </>
                  )}
                </button>

                {isSamePlanDifferentCycle && (
                  <p className="text-xs text-gray-400 mb-4 -mt-2">
                    {t('switchNote')}
                  </p>
                )}

                <ul className="flex flex-col gap-2.5">
                  {plan.features.map((f) => (
                    <li key={f.text} className="flex items-start gap-2 text-sm text-gray-600">
                      <CheckIcon included={f.included} />
                      <span className={f.included ? '' : 'text-gray-400'}>{f.text}</span>
                    </li>
                  ))}
                </ul>
              </div>
            );
          })}
        </div>

        {/* Business tier */}
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-8">
          <div>
            <p className="text-sm font-semibold text-gray-900 mb-1">{t('business.name')}</p>
            <p className="text-sm text-gray-500">{t('business.description')}</p>
          </div>
          <Link
            href="/support"
            className="flex-shrink-0 flex items-center gap-1.5 bg-white border border-gray-300 hover:border-gray-400 text-gray-800 text-sm font-medium px-4 py-2.5 rounded-lg transition-colors whitespace-nowrap"
          >
            {t('business.cta')}
            <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M14 5l7 7m0 0l-7 7m7-7H3" />
            </svg>
          </Link>
        </div>

        <div className="text-center">
          <Link
            href="/pricing"
            className="inline-flex items-center gap-1.5 text-sm font-medium text-brand-purple hover:text-purple-700 transition-colors"
          >
            {t('seeAllPlans')}
          </Link>
        </div>
      </div>
    </section>
  );
}
