"use client";

import { useState } from "react";
import { useApi } from "@/lib/api";
import { useAppStore } from "@/lib/store";
import { Spinner } from "../skeleton";
import { cn } from "@/lib/utils";
import { toPersianDigits, formatToman } from "@/lib/poster";
import { Check, Crown, Zap, Star, Diamond, ShieldCheck } from "lucide-react";

interface Plan {
  id: string; name: string; persianName: string;
  priceMonthly: number; priceQuarterly: number; priceYearly: number;
  maxDevices: number; maxQuality: string; hasPremium: boolean; hasLiveTv: boolean;
  hasMusic: boolean; hasAds: boolean; concurrentStreams: number;
  color: string; features: string[]; sortOrder: number;
}
interface PlansData { plans: Plan[]; }

const PLAN_ICONS: Record<string, any> = {
  free: ShieldCheck, basic: Zap, standard: Star, premium: Crown, vip: Diamond,
};

const PERIOD_LABELS = [
  { key: "priceMonthly", label: "ماهانه", months: 1 },
  { key: "priceQuarterly", label: "سه‌ماهه", months: 3 },
  { key: "priceYearly", label: "سالانه", months: 12 },
];

export function SubscriptionView() {
  const { data, loading } = useApi<PlansData>("/api/subscription/plans");
  const navigate = useAppStore((s) => s.navigate);
  const [period, setPeriod] = useState(0);

  if (loading || !data) return <div className="h-[60vh] flex items-center justify-center"><Spinner /></div>;

  return (
    <div className="px-4 md:px-8 py-8">
      {/* Header */}
      <div className="text-center mb-8 max-w-2xl mx-auto">
        <div className="inline-flex items-center gap-2 rounded-full bg-gradient-brand px-4 py-1.5 text-sm font-bold text-white mb-4">
          <Crown className="h-4 w-4" /> اشتراک PeepBox
        </div>
        <h1 className="text-3xl md:text-5xl font-black mb-3">سرگرمی، بدون مرز</h1>
        <p className="text-muted-foreground">پلن مناسب خود را انتخاب کنید. هر زمان بخواهید ارتقا دهید، کنسل کنید یا تغییر دهید. بدون قرارداد طولانی‌مدت.</p>
      </div>

      {/* Period toggle */}
      <div className="flex justify-center mb-8">
        <div className="inline-flex glass rounded-full p-1">
          {PERIOD_LABELS.map((p, i) => (
            <button
              key={p.key}
              onClick={() => setPeriod(i)}
              className={cn("rounded-full px-4 md:px-6 py-2 text-sm font-bold transition", period === i ? "bg-primary text-white" : "text-muted-foreground hover:text-white")}
            >
              {p.label}
              {p.months === 12 && <span className="mr-1 text-[10px] text-success">۲۰٪ تخفیف</span>}
            </button>
          ))}
        </div>
      </div>

      {/* Plans */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4 mb-12">
        {data.plans.map((plan) => {
          const Icon = PLAN_ICONS[plan.name] ?? Star;
          const price = [plan.priceMonthly, plan.priceQuarterly, plan.priceYearly][period];
          const months = [1, 3, 12][period];
          const perMonth = Math.round(price / months);
          const isPopular = plan.name === "premium";
          const isVip = plan.name === "vip";
          return (
            <div
              key={plan.id}
              className={cn(
                "relative rounded-2xl p-5 flex flex-col transition",
                isPopular ? "bg-gradient-to-b from-primary/20 to-card border-2 border-primary shadow-glow scale-[1.02]" :
                isVip ? "bg-gradient-to-b from-secondary/15 to-card border-2 border-secondary" :
                "glass border border-border",
              )}
            >
              {isPopular && <span className="absolute -top-3 right-1/2 translate-x-1/2 rounded-full bg-gradient-brand px-3 py-0.5 text-[10px] font-bold text-white">محبوب‌ترین</span>}
              {isVip && <span className="absolute -top-3 right-1/2 translate-x-1/2 rounded-full bg-secondary px-3 py-0.5 text-[10px] font-bold text-white">VIP</span>}
              <div className="flex items-center gap-2 mb-1">
                <div className="flex h-10 w-10 items-center justify-center rounded-xl" style={{ background: `${plan.color}30` }}>
                  <Icon className="h-5 w-5" style={{ color: plan.color }} />
                </div>
                <div>
                  <div className="font-black">{plan.persianName}</div>
                  <div className="text-[10px] text-muted-foreground uppercase">{plan.name}</div>
                </div>
              </div>

              <div className="my-4">
                {price === 0 ? (
                  <div className="text-3xl font-black">رایگان</div>
                ) : (
                  <>
                    <div className="text-3xl font-black">{toPersianDigits(perMonth.toLocaleString("en-US"))}<span className="text-sm font-normal text-muted-foreground mr-1">ت/ماه</span></div>
                    <div className="text-xs text-muted-foreground mt-1">پرداخت {toPersianDigits(price.toLocaleString("en-US"))} تومان هر {toPersianDigits(months)} ماه</div>
                  </>
                )}
              </div>

              <ul className="space-y-2 mb-5 flex-1">
                {plan.features.map((f, i) => (
                  <li key={i} className="flex items-start gap-2 text-sm">
                    <Check className="h-4 w-4 text-success shrink-0 mt-0.5" />
                    <span className="text-white/80">{f}</span>
                  </li>
                ))}
                <li className="flex items-center gap-2 text-sm text-muted-foreground">
                  <span className={cn("h-4 w-4 shrink-0 flex items-center justify-center", plan.hasAds ? "text-muted-foreground" : "text-success")}>
                    {plan.hasAds ? "✕" : <Check className="h-4 w-4" />}
                  </span>
                  {plan.hasAds ? "با تبلیغات" : "بدون تبلیغ"}
                </li>
              </ul>

              <button
                onClick={() => navigate("profile")}
                className={cn(
                  "w-full rounded-xl py-3 font-bold text-sm transition",
                  price === 0 ? "glass hover:bg-white/10" : isVip ? "bg-secondary text-white hover:opacity-90" : "bg-gradient-brand text-white hover:opacity-90",
                )}
              >
                {price === 0 ? "استفاده رایگان" : "انتخاب و پرداخت"}
              </button>
            </div>
          );
        })}
      </div>

      {/* Comparison table */}
      <div className="glass rounded-2xl overflow-hidden">
        <h2 className="p-4 font-bold border-b border-border">مقایسه پلن‌ها</h2>
        <div className="overflow-x-auto peepbox-scroll">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border">
                <th className="p-3 text-right text-muted-foreground font-medium">ویژگی</th>
                {data.plans.map((p) => (
                  <th key={p.id} className="p-3 text-center font-bold">{p.persianName}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {[
                { label: "تعداد دستگاه همزمان", get: (p: Plan) => toPersianDigits(p.maxDevices) },
                { label: "حداکثر کیفیت", get: (p: Plan) => p.maxQuality === "2160p" ? "4K UHD" : p.maxQuality },
                { label: "محتوای Premium", get: (p: Plan) => p.hasPremium ? "✓" : "✕" },
                { label: "تلویزیون زنده", get: (p: Plan) => p.hasLiveTv ? "✓" : "✕" },
                { label: "موزیک", get: (p: Plan) => p.hasMusic ? "✓" : "✕" },
                { label: "بدون تبلیغ", get: (p: Plan) => !p.hasAds ? "✓" : "✕" },
                { label: "استریم همزمان", get: (p: Plan) => toPersianDigits(p.concurrentStreams) },
                { label: "قیمت ماهانه", get: (p: Plan) => p.priceMonthly === 0 ? "رایگان" : formatToman(p.priceMonthly) },
              ].map((row, i) => (
                <tr key={i} className="border-b border-border/50 last:border-0">
                  <td className="p-3 text-muted-foreground">{row.label}</td>
                  {data.plans.map((p) => (
                    <td key={p.id} className="p-3 text-center font-medium">{row.get(p)}</td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
