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

const PADDLE_ENABLED = process.env.NEXT_PUBLIC_PADDLE_ENABLED === 'true';

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

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

  // True when arriving from the billing page with a canceled subscription
  const [isResubscribing] = useState(() =>
    typeof window !== 'undefined' &&
    new URLSearchParams(window.location.search).get('resubscribe') === 'true'
  );
  const [loading, setLoading] = useState<UserPlan | null>(null);
  const [checkoutError, setCheckoutError] = useState<string | null>(null);
  const [pendingChange, setPendingChange] = useState<{
    plan: UserPlan;
    billing: BillingCycle;
    isUpgrade: boolean;
    planName: string;
  } | null>(null);

  const PLAN_RANK: Record<UserPlan, number> = { free: 0, basic: 1, premium: 2, max: 3, business: 4 };

  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 (!isResubscribing && user?.plan === plan && (user?.planBillingCycle ?? 'monthly') === effectiveBilling) return;

    setLoading(plan);
    setCheckoutError(null);

    // When resubscribing after cancellation, always create a fresh checkout
    // rather than trying to upgrade a canceled subscription.
    const hasPaidSubscription = !isResubscribing && user?.plan !== 'free';

    if (hasPaidSubscription) {
      const currentRank = PLAN_RANK[user?.plan ?? 'free'];
      const newRank = PLAN_RANK[plan];
      const cycleUpgrade =
        newRank === currentRank &&
        user?.planBillingCycle === 'monthly' &&
        effectiveBilling === 'yearly';
      const isUpgrade = newRank > currentRank || cycleUpgrade;
      const planConfig = PLANS.find((p) => p.id === plan);
      setPendingChange({ plan, billing: effectiveBilling, isUpgrade, planName: planConfig?.name ?? plan });
      setLoading(null);
      return;
    }

    try {
      const result = await createCheckout(plan, effectiveBilling);

      if (result.checkoutUrl) {
        // Creem: redirect to hosted checkout
        window.location.href = result.checkoutUrl;
        return;
      }

      if (result.priceId && PADDLE_ENABLED) {
        // Paddle: open overlay
        if (!paddleInstance) {
          setCheckoutError(t('errors.paymentUnavailable'));
          setLoading(null);
          return;
        }

        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: result.priceId, quantity: 1 }],
          ...(user?.email ? { customer: { email: user.email } } : {}),
          customData: { userId: user?.email ?? '' },
          settings: { displayMode: 'overlay', theme: 'light' },
        });
        return;
      }

      setCheckoutError(t('errors.paymentUnavailable'));
      setLoading(null);
    } catch {
      setCheckoutError(t('errors.checkoutFailed'));
      setLoading(null);
    }
  }

  async function confirmPlanChange() {
    if (!pendingChange) return;
    setLoading(pendingChange.plan);
    setCheckoutError(null);
    const { plan, billing: pendingBilling } = pendingChange;
    setPendingChange(null);
    try {
      const result = await updateSubscription(plan, pendingBilling);
      if (result?.checkoutUrl) {
        window.location.href = result.checkoutUrl;
        return;
      }
      router.push('/billing');
    } catch (err: unknown) {
      const code = (err as any)?.response?.data?.error;
      setCheckoutError(
        code === 'pending_change' ? t('errors.pendingChange') : t('errors.updateFailed')
      );
      setLoading(null);
    }
  }

  // Auto-open checkout when redirected back from sign-in with a plan pre-selected
  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;
    if (billingParam === 'monthly' || billingParam === 'yearly') {
      setBilling(billingParam);
    }
    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 && !isResubscribing) || 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 && !isResubscribing
                        ? '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 />

      {/* Plan change confirmation dialog */}
      {pendingChange && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4">
          <div className="bg-white rounded-2xl shadow-xl p-8 max-w-sm w-full">
            <h3 className="text-base font-semibold text-gray-900 mb-3">
              {pendingChange.isUpgrade ? t('confirmUpgrade.title') : t('confirmDowngrade.title')}
            </h3>
            <p className="text-sm text-gray-500 mb-6">
              {pendingChange.isUpgrade
                ? t('confirmUpgrade.message', { planName: pendingChange.planName })
                : t('confirmDowngrade.message', { planName: pendingChange.planName })}
            </p>
            <div className="flex gap-3">
              <button
                onClick={() => setPendingChange(null)}
                className="flex-1 py-2.5 rounded-lg border border-gray-300 text-sm font-medium text-gray-700 hover:border-gray-400 transition-colors"
              >
                {pendingChange.isUpgrade ? t('confirmUpgrade.cancel') : t('confirmDowngrade.cancel')}
              </button>
              <button
                onClick={confirmPlanChange}
                className={`flex-1 py-2.5 rounded-lg text-sm font-medium text-white transition-colors ${
                  pendingChange.isUpgrade
                    ? 'bg-brand-purple hover:bg-purple-700'
                    : 'bg-gray-700 hover:bg-gray-800'
                }`}
              >
                {pendingChange.isUpgrade ? t('confirmUpgrade.confirm') : t('confirmDowngrade.confirm')}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
