"use client";

import { useState } from "react";
import { motion } from "framer-motion";
import {
  Check,
  Zap,
  Crown,
  Rocket,
  Loader2,
  Sparkles,
} from "lucide-react";
import { useCreateCheckout, useSubscription } from "@/hooks/use-api";
import { useToast } from "@/components/ui/toast";

const plans = [
  {
    name: "Free",
    price: { monthly: 0, yearly: 0 },
    description: "Başlangıç için ideal",
    icon: Zap,
    gradient: "from-gray-500/20 to-gray-600/10",
    iconColor: "text-gray-400",
    features: [
      "Ayda 3 video",
      "720p kalite",
      "Temel AI senaryo",
      "Topluluk desteği",
    ],
    cta: "Mevcut Plan",
    popular: false,
  },
  {
    name: "Pro",
    price: { monthly: 29, yearly: 290 },
    description: "İçerik üreticileri için",
    icon: Crown,
    gradient: "from-violet-500/20 to-cyan-400/10",
    iconColor: "text-violet-400",
    features: [
      "Ayda 50 video",
      "1080p Full HD",
      "Gelişmiş AI senaryo",
      "Tweet → Video dönüşümü",
      "Öncelikli render",
      "E-posta desteği",
    ],
    cta: "Pro'ya Geç",
    popular: true,
  },
  {
    name: "Enterprise",
    price: { monthly: 99, yearly: 990 },
    description: "Ajanslar ve büyük ekipler",
    icon: Rocket,
    gradient: "from-amber-500/20 to-orange-400/10",
    iconColor: "text-amber-400",
    features: [
      "Sınırsız video",
      "4K Ultra HD",
      "Premium AI + özel model",
      "API erişimi",
      "Özel şablonlar",
      "Öncelikli 7/24 destek",
      "Beyaz etiket seçeneği",
    ],
    cta: "Enterprise'a Geç",
    popular: false,
  },
];

export default function PricingPage() {
  const [billingCycle, setBillingCycle] = useState<"monthly" | "yearly">(
    "monthly",
  );
  const checkout = useCreateCheckout();
  const { data: subData } = useSubscription();
  const toast = useToast();

  const currentPlan = subData?.data?.plan ?? subData?.plan ?? "Free";

  const handleCheckout = async (planName: string) => {
    if (planName === "Free") {
      toast.info("Free plan zaten aktif");
      return;
    }
    if (planName === currentPlan) {
      toast.info("Bu plan zaten aktif");
      return;
    }
    try {
      await checkout.mutateAsync({ planName, billingCycle });
    } catch {
      toast.error("Ödeme sayfası açılamadı. Lütfen tekrar deneyin.");
    }
  };

  return (
    <div className="max-w-5xl mx-auto space-y-8">
      {/* Header */}
      <div className="text-center space-y-3">
        <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-violet-500/10 border border-violet-500/20 text-violet-300 text-xs font-medium">
          <Sparkles size={12} />
          Fiyatlandırma
        </div>
        <h1 className="text-3xl md:text-4xl font-[family-name:var(--font-display)] font-bold text-[var(--color-text-primary)]">
          İhtiyacınıza Uygun Plan
        </h1>
        <p className="text-sm text-[var(--color-text-muted)] max-w-lg mx-auto">
          İster hobby, ister profesyonel — her seviyeye uygun planlarımızla AI
          video üretimine başlayın.
        </p>
      </div>

      {/* Billing Toggle */}
      <div className="flex items-center justify-center gap-3">
        <span
          className={`text-sm ${
            billingCycle === "monthly"
              ? "text-[var(--color-text-primary)]"
              : "text-[var(--color-text-muted)]"
          }`}
        >
          Aylık
        </span>
        <button
          onClick={() =>
            setBillingCycle((p) => (p === "monthly" ? "yearly" : "monthly"))
          }
          className={`relative w-12 h-6 rounded-full transition-colors ${
            billingCycle === "yearly"
              ? "bg-violet-500"
              : "bg-[var(--color-bg-elevated)]"
          }`}
        >
          <motion.div
            className="absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white shadow"
            animate={{ x: billingCycle === "yearly" ? 24 : 0 }}
            transition={{ type: "spring", bounce: 0.25, duration: 0.3 }}
          />
        </button>
        <span
          className={`text-sm ${
            billingCycle === "yearly"
              ? "text-[var(--color-text-primary)]"
              : "text-[var(--color-text-muted)]"
          }`}
        >
          Yıllık
          <span className="ml-1 text-xs text-emerald-400 font-medium">
            %17 tasarruf
          </span>
        </span>
      </div>

      {/* Plans Grid */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
        {plans.map((plan, idx) => {
          const isCurrentPlan =
            plan.name.toLowerCase() === currentPlan.toLowerCase();
          const PlanIcon = plan.icon;
          const price = plan.price[billingCycle];

          return (
            <motion.div
              key={plan.name}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: idx * 0.1 }}
              className={`relative card p-6 flex flex-col ${
                plan.popular
                  ? "border-violet-500/30 shadow-lg shadow-violet-500/5"
                  : ""
              }`}
            >
              {plan.popular && (
                <div className="absolute -top-3 left-1/2 -translate-x-1/2 px-3 py-0.5 rounded-full bg-violet-500 text-white text-[10px] font-bold uppercase tracking-wider">
                  En Popüler
                </div>
              )}

              <div
                className={`w-10 h-10 rounded-xl bg-gradient-to-br ${plan.gradient} flex items-center justify-center mb-4`}
              >
                <PlanIcon size={20} className={plan.iconColor} />
              </div>

              <h3 className="text-lg font-bold text-[var(--color-text-primary)]">
                {plan.name}
              </h3>
              <p className="text-xs text-[var(--color-text-muted)] mb-4">
                {plan.description}
              </p>

              <div className="mb-5">
                <span className="text-3xl font-[family-name:var(--font-display)] font-bold text-[var(--color-text-primary)]">
                  ${price}
                </span>
                {price > 0 && (
                  <span className="text-sm text-[var(--color-text-muted)]">
                    /{billingCycle === "monthly" ? "ay" : "yıl"}
                  </span>
                )}
              </div>

              <ul className="space-y-2.5 flex-1 mb-6">
                {plan.features.map((f) => (
                  <li
                    key={f}
                    className="flex items-start gap-2 text-sm text-[var(--color-text-secondary)]"
                  >
                    <Check
                      size={14}
                      className="shrink-0 mt-0.5 text-emerald-400"
                    />
                    {f}
                  </li>
                ))}
              </ul>

              <button
                onClick={() => handleCheckout(plan.name)}
                disabled={
                  isCurrentPlan || (checkout.isPending && !isCurrentPlan)
                }
                className={`w-full py-2.5 rounded-xl text-sm font-semibold transition-all ${
                  isCurrentPlan
                    ? "bg-[var(--color-bg-elevated)] text-[var(--color-text-ghost)] cursor-default"
                    : plan.popular
                      ? "btn-primary"
                      : "bg-[var(--color-bg-elevated)] text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-surface)] border border-[var(--color-border-faint)]"
                }`}
              >
                {checkout.isPending && !isCurrentPlan ? (
                  <Loader2 size={16} className="animate-spin mx-auto" />
                ) : isCurrentPlan ? (
                  "Mevcut Plan"
                ) : (
                  plan.cta
                )}
              </button>
            </motion.div>
          );
        })}
      </div>
    </div>
  );
}
