"use client";

import { useState, useEffect } from "react";
import { Check, Shield, Clock, Zap, ChevronDown } from "lucide-react";
import type { Currency, BillingPeriod } from "@/lib/types/pricing";
import { PRICING_TIERS } from "@/lib/config/pricing-tiers";
import { CurrencyManager } from "@/lib/utils/currency";

interface PackageSelectionProps {
  isAr: boolean;
  defaultTier?: string;
  defaultCurrency?: Currency;
  defaultPeriod?: BillingPeriod;
  onSelectPackage: (
    tierId: string,
    currency: Currency,
    period: BillingPeriod,
  ) => void;
}

export default function PackageSelection({
  isAr,
  defaultTier = "tier2",
  defaultCurrency = "GBP",
  defaultPeriod = "monthly",
  onSelectPackage,
}: PackageSelectionProps) {
  const [selectedTier, setSelectedTier] = useState(defaultTier);
  const [currency, setCurrency] = useState<Currency>(defaultCurrency);
  const [billingPeriod, setBillingPeriod] =
    useState<BillingPeriod>(defaultPeriod);
  const [showCurrencyDropdown, setShowCurrencyDropdown] = useState(false);

  // Sync with parent's currency updates (for auto-detection)
  useEffect(() => {
    setCurrency(defaultCurrency);
  }, [defaultCurrency]);

  const currencyInfo = CurrencyManager.getCurrencyInfo(currency);

  // Calculate price with yearly discount (7% off)
  const calculatePrice = (priceGBP: number): number => {
    const convertedPrice = CurrencyManager.convert(priceGBP, currency);
    if (billingPeriod === "yearly") {
      return convertedPrice * 0.93; // 7% discount
    }
    return convertedPrice;
  };

  const handleContinue = () => {
    onSelectPackage(selectedTier, currency, billingPeriod);
  };

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

  return (
    <div className="w-full max-w-7xl mx-auto">
      {/* Header Section */}
      <div className="text-center mb-10">
        <h2 className="text-4xl md:text-5xl font-bold text-gray-900 mb-4">
          {isAr ? "اختر باقتك" : "Choose Your Plan"}
        </h2>

        <p className="text-lg text-gray-600 max-w-xl mx-auto mb-8">
          {isAr
            ? "ابدأ بتجربة مجانية لمدة 14 يوماً - لا حاجة لبطاقة ائتمان"
            : "Start with a 14-day free trial. No credit card required."}
        </p>

        {/* Trust badges */}
        <div className="flex flex-wrap justify-center gap-3 mb-8">
          {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>

        {/* Controls - Billing Toggle & Currency */}
        <div className="inline-flex flex-col items-center gap-4">
          {/* Billing toggle */}
          <div className="flex bg-gray-100 p-1 rounded-lg">
            <button
              type="button"
              aria-label="Monthly billing"
              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
              type="button"
              aria-label="Yearly billing"
              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
              type="button"
              aria-label="Select currency"
              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">{currency}</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((curr) => {
                  const info = CurrencyManager.getCurrencyInfo(curr);
                  return (
                    <button
                      key={curr}
                      onClick={() => {
                        setCurrency(curr);
                        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 ${
                        currency === curr
                          ? "bg-[#10B981]/10 text-[#10B981]"
                          : "text-gray-700"
                      }`}
                    >
                      <span className="text-lg">{info.symbol}</span>
                      <span className="font-medium">{curr}</span>
                    </button>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Package Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-6 mb-12">
        {PRICING_TIERS.map((tier) => {
          const isSelected = selectedTier === tier.id;
          const price = calculatePrice(tier.priceGBP);
          const name = isAr ? tier.nameAr : tier.nameEn;
          const features = isAr ? tier.featuresAr : tier.featuresEn;
          const displayFeatures = features.slice(0, 5);

          return (
            <button
              key={tier.id}
              onClick={() => setSelectedTier(tier.id)}
              className={`
                relative bg-white rounded-xl border p-6 flex flex-col text-left transition-all duration-300
                hover:shadow-lg hover:-translate-y-1
                ${
                  isSelected
                    ? "border-[#10B981] ring-2 ring-[#10B981]/20 shadow-lg -translate-y-1"
                    : tier.popular
                      ? "border-[#10B981] ring-1 ring-[#10B981]/10"
                      : "border-gray-200"
                }
              `}
            >
              {/* Selected checkmark */}
              {isSelected && (
                <div className="absolute top-3 right-3">
                  <div className="w-6 h-6 rounded-full bg-[#10B981] flex items-center justify-center">
                    <Check className="w-4 h-4 text-white" strokeWidth={3} />
                  </div>
                </div>
              )}

              {/* 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">
                {name}
              </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">
                    {Math.round(price).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">
                  {isAr ? "الإعداد:" : "Setup:"} {currencyInfo.symbol}
                  {Math.round(
                    CurrencyManager.convert(tier.setupGBP, currency),
                  ).toLocaleString()}
                </p>
              </div>

              {/* Features */}
              <ul className="space-y-3 flex-grow">
                {displayFeatures.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>
                ))}
                {features.length > 5 && (
                  <li className="text-sm text-gray-400 pl-8">
                    +{features.length - 5}{" "}
                    {isAr ? "مزايا إضافية" : "more features"}
                  </li>
                )}
              </ul>
            </button>
          );
        })}
      </div>

      {/* Continue Button */}
      <div className="text-center">
        <button
          onClick={handleContinue}
          className="inline-flex items-center gap-2 px-8 py-4 bg-[#10B981] text-white font-semibold text-lg rounded-lg hover:bg-[#059669] transition-colors shadow-lg"
        >
          <span>{isAr ? "متابعة إلى التسجيل" : "Continue to Sign Up"}</span>
          <svg
            className={`w-5 h-5 ${isAr ? "rotate-180" : ""}`}
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
            strokeWidth={2}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M13 7l5 5m0 0l-5 5m5-5H6"
            />
          </svg>
        </button>

        <p className="mt-4 text-sm text-gray-500 flex items-center justify-center gap-2">
          <Check className="w-4 h-4 text-[#10B981]" />
          {isAr
            ? "يمكنك تغيير الباقة في أي وقت بعد التسجيل"
            : "Change your plan anytime after signup"}
        </p>
      </div>
    </div>
  );
}
