"use client";

import { useEffect, useMemo, useState } from "react";
import { X, Check, Crown, CreditCard, Info, Sparkles } from "lucide-react";
import type { Lang } from "@/lib/config";
import type {
  Currency,
  BillingPeriod,
  TierId,
  PricingTier,
} from "@/lib/types/pricing";
import { PRICING_TIERS } from "@/lib/config/pricing-tiers";
import { CurrencyManager } from "@/lib/utils/currency";

interface PricingSelectionModalProps {
  lang: Lang;
  isOpen: boolean;
  onClose: () => void;
  onTierSelected: (
    tierId: TierId,
    billingPeriod: BillingPeriod,
    currency: Currency,
  ) => void;
  defaultTier?: TierId;
  defaultCurrency?: Currency;
  defaultBillingPeriod?: BillingPeriod;
  isSubmitting?: boolean;
  /** When true, removes all close/dismiss controls — user must select a plan */
  required?: boolean;
}

export default function PricingSelectionModal({
  lang,
  isOpen,
  onClose,
  onTierSelected,
  defaultTier,
  defaultCurrency,
  defaultBillingPeriod = "monthly",
  isSubmitting = false,
  required = false,
}: PricingSelectionModalProps) {
  const isAr = lang === "ar";

  // State
  const [selectedTier, setSelectedTier] = useState<TierId>(
    defaultTier ?? PRICING_TIERS.find((tier) => tier.popular)?.id ?? "tier2",
  );
  const [billingPeriod, setBillingPeriod] =
    useState<BillingPeriod>(defaultBillingPeriod);
  const [selectedCurrency, setSelectedCurrency] = useState<Currency>(
    defaultCurrency || "QAR", // Only QAR is supported
  );

  // Update defaults when parent values change
  useEffect(() => {
    if (defaultCurrency) {
      setSelectedCurrency(defaultCurrency);
    }
  }, [defaultCurrency]);

  useEffect(() => {
    if (defaultTier) {
      setSelectedTier(defaultTier);
    }
  }, [defaultTier]);

  useEffect(() => {
    setBillingPeriod(defaultBillingPeriod);
  }, [defaultBillingPeriod]);

  // Translations
  const t = {
    title: isAr ? "اختر باقتك" : "Choose Your Plan",
    subtitle: isAr
      ? "اختر الباقة المناسبة ثم تابع إلى الدفع الآمن"
      : "Choose the right plan, then continue to secure payment",
    monthly: isAr ? "شهري" : "Monthly",
    yearly: isAr ? "سنوي" : "Yearly",
    save: isAr ? "وفر 7%" : "Save 7%",
    popular: isAr ? "الأكثر شعبية" : "Most Popular",
    selectPlan: isAr ? "اختيار الباقة" : "Select Plan",
    selectedPlan: isAr ? "الباقة المحددة" : "Selected Plan",
    continueToPayment: isAr ? "المتابعة إلى الدفع" : "Continue to Payment",
    choosePlanFirst: isAr ? "اختر باقة أولاً" : "Choose a plan first",
    perMonth: isAr ? "/شهر" : "/mo",
    perYear: isAr ? "/سنة" : "/year",
    setupFee: isAr ? "رسوم الإعداد" : "Setup Fee",
    oneTime: isAr ? "مرة واحدة" : "One-time",
    billedAnnually: isAr ? "تجدد سنويًا" : "Billed yearly",
    billedMonthly: isAr ? "تجدد شهريًا" : "Billed monthly",
    currency: isAr ? "العملة" : "Currency",
    close: isAr ? "إغلاق" : "Close",
    paymentNote: isAr
      ? "سيتم إنشاء عميل Stripe ثم تحويلك إلى صفحة الدفع."
      : "We will create your Stripe customer and redirect you to checkout.",
    saveBadge: isAr ? "خصم سنوي" : "Yearly savings",
    includedFeatures: isAr ? "أبرز المزايا" : "Included features",
  };

  // Get all available currencies
  // NOTE: Only QAR is currently supported by the backend checkout API
  // See: app/api/subscriptions/create-checkout/route.ts ALLOWED_CURRENCIES
  const availableCurrencies: Currency[] = ["QAR"];

  // Only show 3 tiers: Starter, Professional, Business
  const visibleTiers = PRICING_TIERS.filter((tier) =>
    ["tier1", "tier2", "tier3"].includes(tier.id),
  );

  // Calculate price for display
  const calculateDisplayPrice = (tier: PricingTier): number => {
    const convertedPrice = CurrencyManager.convert(
      tier.priceGBP,
      selectedCurrency,
    );

    if (billingPeriod === "yearly") {
      // Apply 7% discount for yearly (multiply by 0.93)
      return Math.round(convertedPrice * 0.93);
    }

    return convertedPrice;
  };

  // Calculate setup fee
  const calculateSetupFee = (tier: PricingTier): number => {
    return CurrencyManager.convert(tier.setupGBP, selectedCurrency);
  };

  const selectedTierConfig = useMemo(
    () =>
      PRICING_TIERS.find((tier) => tier.id === selectedTier) ??
      PRICING_TIERS[0],
    [selectedTier],
  );

  const handleConfirmSelection = () => {
    if (!selectedTierConfig) return;
    onTierSelected(selectedTierConfig.id, billingPeriod, selectedCurrency);
  };

  if (!isOpen) return null;

  return (
    <>
      {/* Backdrop */}
      <div
        className="fixed inset-0 bg-black/50 z-40 backdrop-blur-sm"
        onClick={required ? undefined : onClose}
      />

      {/* Modal */}
      <div
        className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto py-8 px-4"
        dir={isAr ? "rtl" : "ltr"}
      >
        <div className="flex max-h-[90vh] w-full max-w-6xl flex-col overflow-hidden rounded-[28px] border border-slate-200 bg-white shadow-2xl">
          {/* Header */}
          <div className="border-b border-slate-200 bg-gradient-to-r from-brand-green/10 via-emerald-50 to-white px-6 py-5">
            <div className="flex flex-wrap items-start justify-between gap-4">
              <div>
                <h2 className="text-2xl font-bold text-slate-900">{t.title}</h2>
                <p className="text-slate-600 mt-1">{t.subtitle}</p>
              </div>
              {!required && (
                <button
                  onClick={onClose}
                  className="p-2 text-slate-400 hover:text-slate-600 hover:bg-white rounded-xl transition-colors"
                >
                  <X className="w-6 h-6" />
                </button>
              )}
            </div>

            {/* Controls */}
            <div className="mt-6 flex flex-wrap items-center gap-3">
              {/* Billing Period Toggle */}
              <div className="inline-flex items-center rounded-xl border border-slate-200 bg-white p-1 shadow-sm">
                <button
                  onClick={() => setBillingPeriod("monthly")}
                  className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
                    billingPeriod === "monthly"
                      ? "bg-brand-green text-white shadow-md"
                      : "text-slate-600 hover:text-slate-900"
                  }`}
                >
                  {t.monthly}
                </button>
                <button
                  onClick={() => setBillingPeriod("yearly")}
                  className={`px-4 py-2 rounded-lg text-sm font-medium transition-all flex items-center gap-2 ${
                    billingPeriod === "yearly"
                      ? "bg-brand-green text-white shadow-md"
                      : "text-slate-600 hover:text-slate-900"
                  }`}
                >
                  {t.yearly}
                  <span
                    className={`rounded-full px-2 py-0.5 text-xs font-semibold ${
                      billingPeriod === "yearly"
                        ? "bg-white/20 text-white"
                        : "bg-emerald-100 text-emerald-700"
                    }`}
                  >
                    {t.save}
                  </span>
                </button>
              </div>

              {/* Currency Selector */}
              {availableCurrencies.length > 1 ? (
                <div className="flex items-center gap-2">
                  <label className="text-sm font-medium text-slate-700">
                    {t.currency}:
                  </label>
                  <select
                    value={selectedCurrency}
                    onChange={(e) =>
                      setSelectedCurrency(e.target.value as Currency)
                    }
                    className="rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-700 transition-colors hover:border-brand-green focus:outline-none focus:ring-2 focus:ring-brand-green/20"
                  >
                    {availableCurrencies.map((currency) => {
                      const info = CurrencyManager.getCurrencyInfo(currency);
                      return (
                        <option key={currency} value={currency}>
                          {currency} ({info.symbol})
                        </option>
                      );
                    })}
                  </select>
                </div>
              ) : (
                <div className="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm text-slate-700 shadow-sm">
                  <span className="font-medium">{t.currency}</span>
                  <span className="text-slate-400">•</span>
                  <span className="font-semibold">{selectedCurrency}</span>
                </div>
              )}

              {/* Yearly Savings Badge */}
              {billingPeriod === "yearly" && (
                <div className="flex items-center gap-2 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2">
                  <Info className="w-4 h-4 text-emerald-600" />
                  <span className="text-sm font-medium text-emerald-700">
                    {t.saveBadge}: {t.save}
                  </span>
                </div>
              )}
            </div>
          </div>

          {/* Pricing Cards Grid */}
          <div className="flex-1 overflow-y-auto px-6 py-6">
            <div className="mb-6 flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4">
              <div className="flex items-start gap-3">
                <div className="rounded-2xl bg-brand-green/10 p-2 text-brand-green">
                  <Sparkles className="h-5 w-5" />
                </div>
                <div>
                  <p className="text-sm font-medium text-slate-500">
                    {t.selectedPlan}
                  </p>
                  <p className="text-lg font-semibold text-slate-900">
                    {isAr
                      ? selectedTierConfig.nameAr
                      : selectedTierConfig.nameEn}
                  </p>
                </div>
              </div>
              <div className="text-right">
                <p className="text-2xl font-bold text-slate-900">
                  {CurrencyManager.getCurrencyInfo(selectedCurrency).symbol}
                  {calculateDisplayPrice(selectedTierConfig)}
                  <span className="ml-1 text-sm font-medium text-slate-500">
                    {billingPeriod === "monthly" ? t.perMonth : t.perYear}
                  </span>
                </p>
                <p className="text-sm text-slate-500">
                  {billingPeriod === "yearly"
                    ? t.billedAnnually
                    : t.billedMonthly}
                </p>
              </div>
            </div>

            <div className="grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3">
              {visibleTiers.map((tier) => {
                const displayPrice = calculateDisplayPrice(tier);
                const setupFee = calculateSetupFee(tier);
                const currencyInfo =
                  CurrencyManager.getCurrencyInfo(selectedCurrency);
                const isPopular = tier.popular;
                const isSelected = tier.id === selectedTier;
                const features = (
                  isAr ? tier.featuresAr : tier.featuresEn
                ).slice(0, 6);

                return (
                  <button
                    key={tier.id}
                    type="button"
                    onClick={() => setSelectedTier(tier.id)}
                    className={`relative flex h-full flex-col rounded-3xl border p-5 text-left transition-all duration-200 ${
                      isSelected
                        ? "border-brand-green bg-emerald-50/40 shadow-xl shadow-brand-green/10 ring-2 ring-brand-green/15"
                        : isPopular
                          ? "border-brand-green/40 bg-white shadow-lg shadow-brand-green/5 hover:-translate-y-0.5 hover:shadow-xl"
                          : "border-slate-200 bg-white hover:-translate-y-0.5 hover:border-slate-300 hover:shadow-lg"
                    }`}
                  >
                    {/* Header badges */}
                    {isPopular && (
                      <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                        <div className="flex items-center gap-1.5 rounded-full bg-gradient-to-r from-brand-green to-emerald-600 px-3 py-1 text-xs font-semibold text-white shadow-lg">
                          <Crown className="w-3.5 h-3.5" />
                          {t.popular}
                        </div>
                      </div>
                    )}

                    {isSelected && (
                      <div className="absolute right-4 top-4 rounded-full bg-brand-green p-1 text-white shadow-md">
                        <Check className="h-4 w-4" />
                      </div>
                    )}

                    <div className="flex h-full flex-col">
                      {/* Tier Name */}
                      <div className="mb-2 flex items-center justify-between gap-3">
                        <h3 className="text-xl font-bold text-slate-900">
                          {isAr ? tier.nameAr : tier.nameEn}
                        </h3>
                        <span
                          className={`rounded-full px-3 py-1 text-xs font-semibold ${
                            isSelected
                              ? "bg-brand-green text-white"
                              : "bg-slate-100 text-slate-600"
                          }`}
                        >
                          {isSelected ? t.selectedPlan : t.selectPlan}
                        </span>
                      </div>

                      <p className="mb-5 text-sm text-slate-500">
                        {tier.id === "tier1"
                          ? isAr
                            ? "الأساسيات اللازمة لبدء التشغيل"
                            : "Core automation for getting started"
                          : tier.id === "tier2"
                            ? isAr
                              ? "أفضل توازن بين التشغيل والأتمتة"
                              : "Best balance of automation and control"
                            : tier.id === "tier3"
                              ? isAr
                                ? "للشركات التي تحتاج فرقًا وسير عمل متقدم"
                                : "For growing teams and advanced workflows"
                              : tier.id === "tier4"
                                ? isAr
                                  ? "للتشغيل متعدد القنوات والإدارة المتقدمة"
                                  : "For advanced operations across channels"
                                : isAr
                                  ? "للاحتياجات الأكثر توسعًا ودعمًا"
                                  : "For the widest operating footprint"}
                      </p>

                      {/* Price */}
                      <div className="mb-5 rounded-2xl bg-slate-50 px-4 py-4">
                        <div className="flex items-baseline gap-1">
                          <span className="text-3xl font-bold text-slate-900">
                            {currencyInfo.symbol}
                            {displayPrice}
                          </span>
                          <span className="text-sm text-slate-500">
                            {billingPeriod === "monthly"
                              ? t.perMonth
                              : t.perYear}
                          </span>
                        </div>

                        <div className="mt-2 text-sm text-slate-500">
                          {t.setupFee}: {currencyInfo.symbol}
                          {setupFee} ({t.oneTime})
                        </div>

                        {billingPeriod === "yearly" && (
                          <div className="mt-3 inline-flex rounded-full bg-emerald-100 px-3 py-1 text-xs font-semibold text-emerald-700">
                            {t.save}
                          </div>
                        )}
                      </div>

                      <div className="mb-3 text-xs font-semibold uppercase tracking-[0.12em] text-slate-400">
                        {t.includedFeatures}
                      </div>

                      {/* Features */}
                      <ul className="space-y-3">
                        {features.map((feature, idx) => (
                          <li
                            key={idx}
                            className="flex items-start gap-2.5 text-sm text-slate-600"
                          >
                            <Check className="mt-0.5 h-4 w-4 shrink-0 text-brand-green" />
                            <span>{feature}</span>
                          </li>
                        ))}
                      </ul>

                      {(isAr ? tier.featuresAr : tier.featuresEn).length >
                        features.length && (
                        <p className="mt-4 text-sm font-medium text-slate-400">
                          +
                          {(isAr ? tier.featuresAr : tier.featuresEn).length -
                            features.length}{" "}
                          {isAr ? "مزايا إضافية" : "more features"}
                        </p>
                      )}
                    </div>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Footer */}
          <div className="border-t border-slate-200 bg-white/95 px-6 py-4 backdrop-blur supports-[backdrop-filter]:bg-white/80">
            <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
              <div>
                <p className="text-sm font-medium text-slate-500">
                  {t.selectedPlan}
                </p>
                <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-slate-600">
                  <span className="font-semibold text-slate-900">
                    {isAr
                      ? selectedTierConfig.nameAr
                      : selectedTierConfig.nameEn}
                  </span>
                  <span>
                    {billingPeriod === "yearly"
                      ? t.billedAnnually
                      : t.billedMonthly}
                  </span>
                  <span>
                    {t.currency}: {selectedCurrency}
                  </span>
                </div>
                <p className="mt-2 text-sm text-slate-500">{t.paymentNote}</p>
              </div>

              <div className="flex flex-col-reverse gap-3 sm:flex-row">
                {!required && (
                  <button
                    onClick={onClose}
                    className="rounded-xl border border-slate-200 px-4 py-3 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-50 hover:text-slate-900"
                  >
                    {t.close}
                  </button>
                )}
                <button
                  onClick={handleConfirmSelection}
                  disabled={!selectedTierConfig || isSubmitting}
                  className="inline-flex min-w-[220px] items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 px-5 py-3 font-semibold text-white shadow-lg shadow-brand-green/20 transition-all hover:shadow-xl hover:shadow-brand-green/30 disabled:cursor-not-allowed disabled:opacity-60"
                >
                  <CreditCard className="h-5 w-5" />
                  <span>
                    {isSubmitting
                      ? t.continueToPayment
                      : selectedTierConfig
                        ? `${t.continueToPayment}`
                        : t.choosePlanFirst}
                  </span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
