"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { type Lang, UI } from "@/lib/config";
import type {
  SerializableStripeProduct,
  BillingPeriod,
  Currency,
} from "@/lib/types/pricing";
import { CurrencyManager } from "@/lib/utils/currency";
import { PRICING_TIERS } from "@/lib/config/pricing-tiers";
import {
  Check,
  ArrowLeft,
  ArrowRight,
  Shield,
  Clock,
  Zap,
  MessageCircle,
  ChevronDown,
} from "lucide-react";
import PricingComparison from "@/components/pricing/PricingComparison";
import { signupStorage } from "@/lib/storage";

interface PricingClientProps {
  lang: Lang;
  dict: (typeof UI)[Lang];
  stripeProducts: SerializableStripeProduct[];
}

export default function PricingClient({
  lang,
  dict,
  stripeProducts,
}: PricingClientProps) {
  const router = useRouter();
  const isAr = lang === "ar";
  const [selectedCurrency, setSelectedCurrency] = useState<Currency>("GBP");
  const [billingPeriod, setBillingPeriod] = useState<BillingPeriod>("monthly");
  const [isChangePlanMode, setIsChangePlanMode] = useState(false);
  const [showCurrencyDropdown, setShowCurrencyDropdown] = useState(false);

  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.search);
    const changePlan = urlParams.get("change_plan") === "true";

    if (changePlan) {
      setIsChangePlanMode(true);
    } else {
      if (typeof window !== "undefined") {
        localStorage.removeItem("signupData");
      }
    }

    setSelectedCurrency(CurrencyManager.detectUserCurrency());
  }, []);

  const currencyInfo = CurrencyManager.getCurrencyInfo(selectedCurrency);

  const calculatePrice = (priceGBP: number): number => {
    if (billingPeriod === "yearly") {
      return priceGBP * 0.93;
    }
    return priceGBP;
  };

  const tiers =
    stripeProducts.length > 0
      ? stripeProducts.map((product) => {
          const tierConfig = PRICING_TIERS.find((t) => t.id === product.tierId);
          const gbpPrice = product.prices.find(
            (p) => p.currency === "gbp" && p.interval === "month",
          );
          const priceGBP = gbpPrice
            ? gbpPrice.unitAmount / 100
            : tierConfig?.priceGBP || 0;

          return {
            id: product.tierId,
            stripeProductId: product.stripeProductId,
            nameEn: tierConfig?.nameEn || product.name,
            nameAr: tierConfig?.nameAr || product.name,
            priceGBP: priceGBP,
            setupGBP:
              tierConfig?.setupGBP || (product.tierId === "tier5" ? 299 : 199),
            popular: product.tierId === "tier2",
            featuresEn: tierConfig?.featuresEn || product.features || [],
            featuresAr: tierConfig?.featuresAr || product.features || [],
            stripePrices: product.prices,
          };
        })
      : PRICING_TIERS;

  // Only show Starter, Professional, Business for launch
  const visibleTiers = tiers.filter((t) =>
    ["tier1", "tier2", "tier3"].includes(t.id),
  );

  const handleGetStarted = (tierId: string) => {
    if (isChangePlanMode) {
      if (typeof window !== "undefined") {
        const signupData = JSON.parse(
          localStorage.getItem("signupData") || "{}",
        );
        signupData.plan = {
          tierId,
          stripePriceId: "",
          billingPeriod,
          currency: selectedCurrency,
        };
        localStorage.setItem("signupData", JSON.stringify(signupData));
      }
      router.push(`/${lang}/signup/company-info`);
    } else {
      signupStorage.save({
        plan: {
          tierId,
          stripePriceId: "",
          billingPeriod,
          currency: selectedCurrency,
        },
        createdAt: new Date().toISOString(),
        email: "",
        fullName: "",
        verified: false,
      });
      router.push(
        `/${lang}/clerk-signup?redirect_url=${encodeURIComponent(`/${lang}/onboarding`)}`,
      );
    }
  };

  const trustBadges = [
    {
      icon: Shield,
      labelEn: "Bank-Grade Security",
      labelAr: "أمان بمستوى البنوك",
    },
    {
      icon: Clock,
      labelEn: "14-Day Free Trial",
      labelAr: "تجربة مجانية 14 يوم",
    },
    {
      icon: MessageCircle,
      labelEn: "WhatsApp Integration",
      labelAr: "تكامل واتساب",
    },
    { icon: Zap, labelEn: "Instant Setup", labelAr: "إعداد فوري" },
  ];

  return (
    <main
      dir={dict.dir}
      className="min-h-screen bg-gray-50"
      style={{
        fontFamily: isAr
          ? "IBM Plex Sans Arabic, system-ui, sans-serif"
          : "system-ui, -apple-system, sans-serif",
      }}
    >
      {/* Change Plan Mode Banner */}
      {isChangePlanMode && (
        <div className="bg-[#10B981] text-white py-4">
          <div className="max-w-7xl mx-auto px-6 text-center">
            <p className="text-lg font-semibold">
              {isAr
                ? "تغيير الباقة - اختر الباقة الجديدة وسنقوم بتحديث معلوماتك"
                : "Change Plan - Select your new package and we'll update your details"}
            </p>
          </div>
        </div>
      )}

      {/* Hero Section */}
      <section className="pt-24 pb-16 bg-white border-b border-gray-100">
        <div className="max-w-7xl mx-auto px-6">
          {isChangePlanMode && (
            <button
              onClick={() => router.push(`/${lang}/signup/company-info`)}
              className="mb-8 flex items-center gap-2 text-sm text-gray-500 hover:text-[#10B981] transition-colors group"
            >
              {isAr ? (
                <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
              ) : (
                <ArrowLeft className="w-4 h-4 group-hover:-translate-x-1 transition-transform" />
              )}
              {isAr ? "العودة إلى معلومات الشركة" : "Back to Company Info"}
            </button>
          )}

          <div className="text-center max-w-3xl mx-auto">
            <h1 className="text-4xl md:text-5xl font-bold text-gray-900 mb-6">
              {isChangePlanMode ? (
                <span>
                  {isAr ? "اختر باقتك الجديدة" : "Select Your New Plan"}
                </span>
              ) : (
                <>
                  {isAr ? "أسعار بسيطة وشفافة" : "Simple, transparent pricing"}
                </>
              )}
            </h1>

            <p className="text-lg text-gray-600 mb-8">
              {isChangePlanMode
                ? isAr
                  ? "اختر الباقة الجديدة وسيتم تحديث حسابك تلقائياً."
                  : "Select your new package and your account will be updated automatically."
                : isAr
                  ? "بدون رسوم مخفية. بدون مفاجآت. اختر الباقة المناسبة لنمو عملك."
                  : "No hidden fees. No surprises. Choose a plan that scales with your business."}
            </p>

            {/* Trust badges */}
            <div className="flex flex-wrap justify-center gap-4 mb-10">
              {trustBadges.map((badge, idx) => (
                <div
                  key={idx}
                  className="flex items-center gap-2 px-4 py-2 bg-gray-50 border border-gray-200 rounded-full"
                >
                  <badge.icon className="w-4 h-4 text-[#10B981]" />
                  <span className="text-sm text-gray-700">
                    {isAr ? badge.labelAr : badge.labelEn}
                  </span>
                </div>
              ))}
            </div>

            {/* Billing toggle */}
            <div className="inline-flex flex-col items-center gap-4">
              <div className="flex bg-gray-100 p-1 rounded-lg">
                <button
                  onClick={() => setBillingPeriod("monthly")}
                  className={`px-6 py-2.5 rounded-md font-medium text-sm transition-all ${
                    billingPeriod === "monthly"
                      ? "bg-white text-gray-900 shadow-sm"
                      : "text-gray-600 hover:text-gray-900"
                  }`}
                >
                  {isAr ? "شهرياً" : "Monthly"}
                </button>
                <button
                  onClick={() => setBillingPeriod("yearly")}
                  className={`px-6 py-2.5 rounded-md font-medium text-sm transition-all relative ${
                    billingPeriod === "yearly"
                      ? "bg-white text-gray-900 shadow-sm"
                      : "text-gray-600 hover:text-gray-900"
                  }`}
                >
                  {isAr ? "سنوياً" : "Yearly"}
                  <span className="absolute -top-2 -right-2 px-1.5 py-0.5 bg-[#10B981] text-white text-xs font-medium rounded">
                    -7%
                  </span>
                </button>
              </div>

              {billingPeriod === "yearly" && (
                <p className="text-sm text-[#10B981] font-medium">
                  {isAr
                    ? "وفر 7% على الفوترة السنوية"
                    : "Save 7% on annual billing"}
                </p>
              )}

              {/* Currency Selector */}
              <div className="relative">
                <button
                  onClick={() => setShowCurrencyDropdown(!showCurrencyDropdown)}
                  className="flex items-center gap-2 px-4 py-2 bg-white border border-gray-200 rounded-lg hover:border-[#10B981] transition-colors"
                >
                  <span className="text-lg">{currencyInfo.symbol}</span>
                  <span className="font-medium text-gray-900">
                    {selectedCurrency}
                  </span>
                  <ChevronDown
                    className={`w-4 h-4 text-gray-400 transition-transform ${showCurrencyDropdown ? "rotate-180" : ""}`}
                  />
                </button>

                {showCurrencyDropdown && (
                  <div className="absolute top-full mt-2 w-40 bg-white border border-gray-200 rounded-lg shadow-lg z-50">
                    {CurrencyManager.getAllCurrencies().map((currency) => {
                      const info = CurrencyManager.getCurrencyInfo(currency);
                      return (
                        <button
                          key={currency}
                          onClick={() => {
                            setSelectedCurrency(currency);
                            setShowCurrencyDropdown(false);
                          }}
                          className={`w-full px-4 py-2.5 flex items-center gap-3 hover:bg-gray-50 transition-colors text-left first:rounded-t-lg last:rounded-b-lg ${
                            selectedCurrency === currency
                              ? "bg-[#10B981]/10 text-[#10B981]"
                              : "text-gray-700"
                          }`}
                        >
                          <span className="text-lg">{info.symbol}</span>
                          <span className="font-medium">{currency}</span>
                        </button>
                      );
                    })}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Pricing Cards */}
      <section className="py-16">
        <div className="max-w-7xl mx-auto px-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {visibleTiers.map((tier) => {
              const discountedPrice = calculatePrice(tier.priceGBP);
              const convertedPrice = CurrencyManager.convert(
                discountedPrice,
                currencyInfo.code,
              );
              const convertedSetup = CurrencyManager.convert(
                tier.setupGBP,
                currencyInfo.code,
              );
              const features = isAr ? tier.featuresAr : tier.featuresEn;

              return (
                <div
                  key={tier.id}
                  data-testid="pricing-card"
                  data-tier={tier.id}
                  className={`relative bg-white rounded-xl border p-6 flex flex-col transition-all duration-300 hover:shadow-lg hover:-translate-y-1 ${
                    tier.popular
                      ? "border-[#10B981] ring-2 ring-[#10B981]/20"
                      : "border-gray-200"
                  }`}
                >
                  {/* Popular badge */}
                  {tier.popular && (
                    <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                      <span className="px-3 py-1 bg-[#10B981] text-white text-xs font-semibold rounded-full">
                        {isAr ? "الأكثر شعبية" : "Most Popular"}
                      </span>
                    </div>
                  )}

                  {/* Tier name */}
                  <h3 className="text-lg font-bold text-gray-900 mb-2 mt-2">
                    {isAr ? tier.nameAr : tier.nameEn}
                  </h3>

                  {/* Price */}
                  <div className="mb-6">
                    <div className="flex items-baseline gap-1">
                      <span className="text-gray-500 text-lg">
                        {currencyInfo.symbol}
                      </span>
                      <span
                        className="text-4xl font-bold text-gray-900"
                        suppressHydrationWarning
                      >
                        {Math.round(convertedPrice).toLocaleString()}
                      </span>
                      <span className="text-gray-500">
                        /{isAr ? "شهر" : "mo"}
                      </span>
                    </div>
                    {billingPeriod === "yearly" && (
                      <p className="text-xs text-[#10B981] mt-1 font-medium">
                        {isAr ? "فواتير سنوية" : "Billed annually"}
                      </p>
                    )}
                    <p
                      className="text-sm text-gray-500 mt-2"
                      suppressHydrationWarning
                    >
                      {isAr ? "الإعداد:" : "Setup:"} {currencyInfo.symbol}
                      {Math.round(convertedSetup).toLocaleString()}
                    </p>
                  </div>

                  {/* CTA Button */}
                  <button
                    onClick={() => handleGetStarted(tier.id)}
                    data-tier-id={tier.id}
                    data-stripe-product-id={tier.stripeProductId}
                    className={`w-full py-3 rounded-lg font-semibold text-sm flex items-center justify-center gap-2 transition-all mb-6 ${
                      tier.popular
                        ? "bg-[#10B981] text-white hover:bg-[#059669]"
                        : "bg-gray-900 text-white hover:bg-gray-800"
                    }`}
                  >
                    <span>
                      {isChangePlanMode
                        ? isAr
                          ? "اختر هذه الباقة"
                          : "Select Plan"
                        : isAr
                          ? "ابدأ الآن"
                          : "Get Started"}
                    </span>
                    <ArrowRight
                      className={`w-4 h-4 ${isAr ? "rotate-180" : ""}`}
                    />
                  </button>

                  {/* Features */}
                  <ul className="space-y-3 flex-grow">
                    {features.slice(0, 5).map((feature, idx) => (
                      <li key={idx} className="flex items-start gap-3">
                        <Check className="w-5 h-5 text-[#10B981] flex-shrink-0" />
                        <span className="text-sm text-gray-600">{feature}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* Comparison Table */}
      <section className="py-16 bg-white">
        <div className="max-w-7xl mx-auto px-6">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold text-gray-900 mb-4">
              {isAr ? "مقارنة الباقات" : "Compare all features"}
            </h2>
            <p className="text-gray-600">
              {isAr
                ? "اختر الباقة المناسبة لاحتياجات عملك"
                : "Choose the plan that fits your business needs"}
            </p>
          </div>
          <PricingComparison tiers={visibleTiers} isAr={isAr} />
        </div>
      </section>

      {/* FAQ Section */}
      <section className="py-16">
        <div className="max-w-4xl mx-auto px-6">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold text-gray-900 mb-4">
              {isAr ? "الأسئلة الشائعة" : "Frequently asked questions"}
            </h2>
          </div>

          <div className="grid md:grid-cols-2 gap-6">
            {[
              {
                qEn: "Can I cancel anytime?",
                qAr: "هل يمكنني الإلغاء في أي وقت؟",
                aEn: "Yes. No hidden fees. No penalties. Cancel whenever you want.",
                aAr: "نعم. بدون رسوم مخفية. بدون غرامات. ألغِ متى شئت.",
              },
              {
                qEn: "Is the 14-day trial really free?",
                qAr: "هل التجربة المجانية 14 يوم مجانية فعلاً؟",
                aEn: "Absolutely. Full access to all features. No credit card required.",
                aAr: "بالتأكيد. وصول كامل لجميع المزايا. بدون بطاقة ائتمان.",
              },
              {
                qEn: "Can I upgrade or downgrade later?",
                qAr: "هل يمكنني الترقية أو التخفيض لاحقاً؟",
                aEn: "Yes. Changes take effect immediately. Prorated billing.",
                aAr: "نعم. التغييرات تسري فوراً. فوترة تناسبية.",
              },
              {
                qEn: "What payment methods do you accept?",
                qAr: "ما طرق الدفع المقبولة؟",
                aEn: "All major cards, bank transfers, and digital wallets.",
                aAr: "جميع البطاقات الرئيسية، التحويلات البنكية، والمحافظ الرقمية.",
              },
            ].map((faq, idx) => (
              <div
                key={idx}
                className="bg-white rounded-xl border border-gray-200 p-6"
              >
                <h3 className="font-semibold text-gray-900 mb-2">
                  {isAr ? faq.qAr : faq.qEn}
                </h3>
                <p className="text-sm text-gray-600">
                  {isAr ? faq.aAr : faq.aEn}
                </p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* CTA Section */}
      <section className="py-20 bg-white border-t border-gray-100">
        <div className="max-w-3xl mx-auto px-6 text-center">
          <h2 className="text-3xl md:text-4xl font-bold text-gray-900 mb-4">
            {isAr ? "جاهز للتحول؟" : "Ready to get started?"}
          </h2>

          <p className="text-lg text-gray-600 mb-8">
            {isAr
              ? "انضم لأكثر من 500 شركة تستخدم مواعيدي لتبسيط مواعيدها وزيادة إيراداتها."
              : "Join 500+ businesses already using Mawidi to streamline their appointments and grow their revenue."}
          </p>

          <div className="flex flex-col sm:flex-row gap-4 justify-center">
            <button
              onClick={() => handleGetStarted("tier2")}
              className="px-8 py-3.5 bg-[#10B981] text-white font-semibold rounded-lg flex items-center justify-center gap-2 hover:bg-[#059669] transition-colors"
            >
              <span>{isAr ? "ابدأ تجربتك المجانية" : "Start Free Trial"}</span>
              <ArrowRight className={`w-5 h-5 ${isAr ? "rotate-180" : ""}`} />
            </button>
            <a
              href={`/${lang}/contact`}
              className="px-8 py-3.5 border-2 border-gray-200 text-gray-900 font-semibold rounded-lg hover:border-[#10B981] hover:text-[#10B981] transition-colors"
            >
              {isAr ? "تواصل مع المبيعات" : "Contact Sales"}
            </a>
          </div>

          <div className="flex flex-wrap gap-6 justify-center mt-8 text-sm text-gray-500">
            <span className="flex items-center gap-2">
              <Check className="w-4 h-4 text-[#10B981]" />
              {isAr ? "بدون بطاقة ائتمان" : "No credit card required"}
            </span>
            <span className="flex items-center gap-2">
              <Check className="w-4 h-4 text-[#10B981]" />
              {isAr ? "تجربة 14 يوم" : "14-day free trial"}
            </span>
            <span className="flex items-center gap-2">
              <Check className="w-4 h-4 text-[#10B981]" />
              {isAr ? "إلغاء في أي وقت" : "Cancel anytime"}
            </span>
          </div>
        </div>
      </section>
    </main>
  );
}
