'use client';

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

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 PricingPage() {
  const { isAuthenticated, user, createCheckout, verifyTransaction, updateSubscription, hasHydrated } = useAuthStore();
  const router = useRouter();
  const autoTriggered = useRef(false);
  const t = useTranslations('pricing');

  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 },
      ],
    },
  ];

  // Initialise billing from URL param (set when redirected back from sign-in), else from user's current cycle
  const [billing, setBilling] = useState<BillingCycle>(() => {
    if (typeof window !== 'undefined') {
      const b = new URLSearchParams(window.location.search).get('billing');
      if (b === 'monthly' || b === 'yearly') return b;
    }
    return user?.planBillingCycle ?? 'monthly';
  });
  const [loading, setLoading] = useState<UserPlan | null>(null);
  const [checkoutError, setCheckoutError] = useState<string | null>(null);

  // billingOverride is used by the auto-trigger effect to pass the billing cycle
  // read directly from the URL, bypassing the React state which may still hold its
  // SSR-initialised value ('monthly') at the time the effect fires.
  async function handleSelectPlan(plan: UserPlan, billingOverride?: BillingCycle) {
    const effectiveBilling = billingOverride ?? billing;

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

    setLoading(plan);
    setCheckoutError(null);

    // Users already on a paid Paddle subscription: update silently via the API.
    // Users on the free plan: open Paddle checkout to collect payment details.
    const hasPaidSubscription = user?.plan !== 'free';

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

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

    try {
      // BE returns the correct priceId — FE never decides which price to use
      const priceId = await createCheckout(plan, effectiveBilling);

      // Register handlers BEFORE opening the overlay so no events are missed
      setPaddleCheckoutHandlers({
        onCompleted: async (transactionId) => {
          try {
            // Send only the transactionId — plan is verified server-side from Paddle data
            await verifyTransaction(transactionId);
            router.push('/');
          } catch {
            setCheckoutError(t('errors.activationFailed'));
            setLoading(null);
          }
        },
        onClosed: () => setLoading(null),
      });

      paddleInstance.Checkout.open({
        items: [{ priceId, quantity: 1 }],
        // Only pass customer if we have a definite email (guarded by isAuthenticated check above)
        ...(user?.email ? { customer: { email: user.email } } : {}),
        // customData is echoed back in webhooks for server-side user lookup
        customData: { userId: user?.email ?? '' },
        settings: { displayMode: 'overlay', theme: 'light' },
      });
    } catch {
      setCheckoutError(t('errors.checkoutFailed'));
      setLoading(null);
    }
  }

  // Auto-open Paddle checkout when the user was redirected here after signing in
  // with a plan pre-selected (URL params ?plan=X&billing=Y set by the pricing page redirect).
  useEffect(() => {
    if (autoTriggered.current) return;
    if (!hasHydrated || !isAuthenticated) return;
    const params = new URLSearchParams(window.location.search);
    const planParam = params.get('plan') as UserPlan | null;
    const billingParam = params.get('billing') as BillingCycle | null;
    if (!planParam || planParam === 'free' || planParam === 'business') return;
    autoTriggered.current = true;
    // Sync the billing toggle UI to the URL value (the useState initializer may have
    // used the SSR fallback 'monthly' since window is unavailable on the server).
    if (billingParam === 'monthly' || billingParam === 'yearly') {
      setBilling(billingParam);
    }
    // Pass billing explicitly so handleSelectPlan doesn't read the stale state value.
    handleSelectPlan(planParam, billingParam ?? undefined);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hasHydrated, isAuthenticated]);

  return (
    <div className="min-h-screen flex flex-col bg-[#F5F4F0]">
      <Navbar />
      <main className="flex-1 pt-[57px]">
        <div className="max-w-5xl mx-auto px-6 py-16">

          <div className="text-center mb-10">
            <h1 className="text-3xl font-bold text-gray-900 mb-2">{t('headingPage')}</h1>
            <p className="text-gray-500 text-sm">{t('subheading')}</p>
          </div>

          {/* Billing toggle */}
          <div className="flex items-center justify-center gap-2 mb-10">
            <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">
            {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>
                  <h2 className="text-3xl font-bold text-gray-900 mb-1">
                    {price === 0 ? t('plans.free.name') : `€${price?.toFixed(2)}`}
                    {price !== 0 && <span className="text-base font-normal text-gray-400">{t('perMonth')}</span>}
                  </h2>
                  {billing === 'yearly' && plan.yearlyTotal !== null && plan.yearlyTotal > 0 && (
                    <p className="text-xs text-gray-400 mb-1">{t('billedYearlyLabel', { total: plan.yearlyTotal })}</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="mt-4 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">
            <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>
      </main>
      <Footer />
    </div>
  );
}
