"use client";

import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import { Check, ArrowRight } from "lucide-react";
import type { Locale } from "@/lib/i18n";
import { getDictionary } from "@/lib/dictionary";

interface PricingProps {
  locale: Locale;
}

interface PricingPlan {
  id: string;
  key: string;
  nameEn: string;
  nameAr: string;
  descEn: string;
  descAr: string;
  priceEn: string;
  priceAr: string;
  currency?: string;
  period?: string;
  popular: boolean;
  isTrial?: boolean;
  isBase?: boolean;
  trialDays?: number;
  featuresEn: string[];
  featuresAr: string[];
  ctaEn: string;
  ctaAr: string;
  sortOrder: number;
}

const CURRENCY_SYMBOL: Record<string, string> = { USD: "$", EGP: "ج.م ", SAR: "﷼ ", AED: "د.إ ", EUR: "€" };

export function Pricing({ locale }: PricingProps) {
  const [annual, setAnnual] = useState(true);
  const [plans, setPlans] = useState<PricingPlan[]>([]);
  const [loading, setLoading] = useState(true);
  const isRTL = locale === "ar";
  const dict = getDictionary(locale);
  const t = dict.landing.pricing;

  useEffect(() => {
    fetch("/api/landing/pricing")
      .then(res => res.json())
      .then(data => setPlans(data.plans))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  return (
    <section id="pricing" className="relative py-24 md:py-32 overflow-hidden" dir={isRTL ? "rtl" : "ltr"}>
      <div className="absolute inset-0 bg-gradient-to-b from-void-black via-graphite to-void-black" />
      <div className="absolute inset-0 dot-grid-cyan opacity-20" />

      <div className="container-custom relative z-10">
        {/* Header */}
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true, margin: "-100px" }}
          className="text-center mb-12"
        >
          <h2 className="font-space-grotesk font-bold text-3xl md:text-5xl lg:text-6xl tracking-tight mb-4">
            <span className="text-warm-white">{t.title} </span>
            <span className="text-gradient-cyan">{t.titleHighlight}</span>
          </h2>
          <p className="text-base md:text-lg text-muted-white max-w-xl mx-auto leading-relaxed mb-8">
            {t.subtitle}
          </p>

          {/* Toggle */}
          <div className="inline-flex items-center gap-3 p-1 rounded-xl border border-white/[0.06] bg-white/[0.03]">
            <button
              onClick={() => setAnnual(false)}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
                !annual ? "bg-electric-cyan text-void-black" : "text-muted-white hover:text-warm-white"
              }`}
            >
              {t.monthly}
            </button>
            <button
              onClick={() => setAnnual(true)}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
                annual ? "bg-electric-cyan text-void-black" : "text-muted-white hover:text-warm-white"
              }`}
            >
              {t.annual}
              <span className="ml-1.5 text-[10px] opacity-70">-20%</span>
            </button>
          </div>
        </motion.div>

        {/* Cards */}
        <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-4 max-w-6xl mx-auto">
          {loading ? (
            Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="rounded-2xl border border-white/[0.06] p-6 animate-pulse">
                <div className="h-6 bg-white/5 rounded w-24 mb-4" />
                <div className="h-4 bg-white/5 rounded w-48 mb-6" />
                <div className="h-10 bg-white/5 rounded w-32 mb-6" />
                {Array.from({ length: 5 }).map((_, j) => (
                  <div key={j} className="h-4 bg-white/5 rounded w-full mb-3" />
                ))}
              </div>
            ))
          ) : (
            plans.map((plan, i) => {
              const isPopular = plan.popular;
              const name = locale === "en" ? plan.nameEn : plan.nameAr;
              const desc = locale === "en" ? plan.descEn : plan.descAr;
              const price = locale === "en" ? plan.priceEn : plan.priceAr;
              const features = locale === "en" ? plan.featuresEn : plan.featuresAr;
              const cta = locale === "en" ? plan.ctaEn : plan.ctaAr;
              const isCustom = price.toLowerCase() === "custom" || price === "مخصص";
              const symbol = CURRENCY_SYMBOL[plan.currency || "USD"] || "$";
              const displayPrice = isCustom
                ? (locale === "en" ? "Custom" : "مخصص")
                : (plan.currency === "USD" || !plan.currency ? `${symbol}${price}` : `${price} ${symbol}`.trim());
              const periodLabel = plan.period === "year" ? (locale === "en" ? "/year" : "/سنة") : plan.period === "once" ? "" : t.perMonth;
              const trialLabel = plan.isTrial
                ? (locale === "en" ? `${plan.trialDays ?? 14}-day free trial` : `${plan.trialDays ?? 14} يوماً تجربة مجانية`)
                : null;

              return (
                <motion.div
                  key={plan.id}
                  initial={{ opacity: 0, y: 20 }}
                  whileInView={{ opacity: 1, y: 0 }}
                  viewport={{ once: true }}
                  transition={{ delay: i * 0.1, duration: 0.5 }}
                  className={`relative group rounded-2xl border p-6 transition-all duration-500 ${
                    isPopular
                      ? "border-electric-cyan/30 bg-gradient-to-b from-electric-cyan/[0.04] to-transparent"
                      : "border-white/[0.06] bg-white/[0.02] hover:border-white/10"
                  }`}
                >
                  {isPopular && (
                    <div className="absolute -top-3 left-1/2 -translate-x-1/2 px-4 py-1 rounded-full bg-electric-cyan text-void-black text-xs font-semibold font-jetbrains-mono tracking-wider">
                      {t.popular}
                    </div>
                  )}

                  <div className={`${isPopular ? "mt-2" : ""}`}>
                    <div className="flex items-center gap-2 mb-1">
                      <h3 className="font-space-grotesk font-bold text-xl text-warm-white">{name}</h3>
                      {trialLabel && (
                        <span className="rounded-full bg-soft-emerald/15 text-soft-emerald px-2 py-0.5 text-[10px] font-semibold">
                          {trialLabel}
                        </span>
                      )}
                    </div>
                    <p className="text-sm text-muted-white mb-6">{desc}</p>

                    <div className="mb-6">
                      <span className="font-space-grotesk font-bold text-4xl text-warm-white">{displayPrice}</span>
                      {!isCustom && periodLabel && (
                        <span className="text-muted-white text-sm ml-1">{periodLabel}</span>
                      )}
                    </div>

                    <ul className="space-y-3 mb-8">
                      {features.map((feature, j) => (
                        <li key={j} className="flex items-start gap-2.5 text-sm text-muted-white">
                          <Check size={16} className="text-soft-emerald shrink-0 mt-0.5" />
                          <span>{feature}</span>
                        </li>
                      ))}
                    </ul>

                    <motion.a
                      href={isCustom || plan.key === "enterprise" ? "https://wa.me/966544877622" : `/register?plan=${encodeURIComponent(plan.key)}`}
                      target={isCustom || plan.key === "enterprise" ? "_blank" : undefined}
                      rel={isCustom || plan.key === "enterprise" ? "noopener noreferrer" : undefined}
                      whileHover={{ scale: 1.02 }}
                      whileTap={{ scale: 0.98 }}
                      className={`flex items-center justify-center gap-2 w-full py-3.5 rounded-xl font-semibold text-sm font-space-grotesk transition-all ${
                        isPopular
                          ? "bg-gradient-to-r from-electric-cyan to-soft-emerald text-void-black hover:shadow-lg hover:shadow-electric-cyan/20"
                          : "border border-white/10 text-warm-white hover:bg-white/5"
                      }`}
                    >
                      {cta}
                      <ArrowRight size={16} />
                    </motion.a>
                  </div>
                </motion.div>
              );
            })
          )}
        </div>
      </div>
    </section>
  );
}
