import { useEffect, useState } from "react"
import { useNavigate } from "react-router-dom"
import { motion } from "framer-motion"
import { Check, Sparkles, Zap, ArrowLeft, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import stripeService, { type StripePlan, type SubscriptionStatus } from "@/api/stripe"
import useAuth from "@/hooks/useAuth"

export default function Pricing() {
  const navigate = useNavigate()
  const { isAuthenticated } = useAuth()
  const [plans, setPlans] = useState<StripePlan[]>([])
  const [subscription, setSubscription] = useState<SubscriptionStatus | null>(null)
  const [loading, setLoading] = useState(true)
  const [checkoutLoading, setCheckoutLoading] = useState<string | null>(null)
  const [error, setError] = useState("")

  useEffect(() => {
    const load = async () => {
      try {
        const [{ plans }, sub] = await Promise.all([
          stripeService.getPlans(),
          isAuthenticated
            ? stripeService.getSubscription().catch(() => null)
            : Promise.resolve(null),
        ])
        setPlans(plans)
        setSubscription(sub)
      } catch {
        setError("Impossible de charger les plans")
      } finally {
        setLoading(false)
      }
    }
    load()
  }, [isAuthenticated])

  const handleCheckout = async (planId: "essential" | "premium") => {
    if (!isAuthenticated) {
      navigate("/auth/login")
      return
    }
    setCheckoutLoading(planId)
    setError("")
    try {
      await stripeService.startCheckout(planId)
      // Redirection gérée par startCheckout
    } catch (err) {
      setError(err instanceof Error ? err.message : "Erreur de paiement")
      setCheckoutLoading(null)
    }
  }

  // Plan statique "Gratuit" (pas dans les plans Stripe)
  const freePlan = {
    id: "free" as const,
    name: "Gratuit",
    description: "Pour découvrir Freedge",
    features: [
      "5 recettes au total",
      "Reconnaissance vocale",
      "Recettes personnalisées",
      "Sauvegarde des recettes",
    ],
  }

  const currentPlan = subscription?.plan || "free"

  return (
    <div className="mx-auto max-w-6xl px-4 md:px-8 py-6 md:py-12">
      {/* Top bar */}
      <div className="mb-8 flex items-center justify-between">
        <Button
          variant="ghost"
          size="sm"
          className="rounded-full -ml-2 gap-1.5 hover:bg-white/60 dark:hover:bg-slate-800/60"
          onClick={() => navigate(-1)}
        >
          <ArrowLeft className="h-4 w-4" />
          Retour
        </Button>
      </div>

      {/* Hero */}
      <motion.div
        className="text-center mb-12"
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
      >
        <div className="inline-flex items-center gap-1.5 rounded-full bg-gradient-to-r from-orange-100 to-amber-100 dark:from-orange-900/40 dark:to-amber-900/40 px-3 py-1 text-xs font-medium text-orange-700 dark:text-orange-300 border border-orange-200/60 dark:border-orange-800/40 mb-4">
          <Sparkles className="h-3 w-3" />
          Choisis ton plan
        </div>
        <h1 className="text-4xl md:text-5xl font-bold tracking-tight">
          Trouve le plan qui te va
        </h1>
        <p className="text-muted-foreground mt-3 max-w-xl mx-auto text-base md:text-lg">
          Change ou annule à tout moment. Pas d'engagement, pas de frais cachés.
        </p>
      </motion.div>

      {error && (
        <div className="mb-6 max-w-md mx-auto rounded-xl bg-red-50 border border-red-200 p-4 text-sm text-red-800 text-center">
          {error}
        </div>
      )}

      {/* Plans grid */}
      {loading ? (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {[1, 2, 3].map((i) => (
            <div
              key={i}
              className="h-[500px] rounded-2xl bg-muted/60 animate-pulse"
            />
          ))}
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {/* Plan gratuit */}
          <PlanCard
            plan={{
              ...freePlan,
              price: "0€",
              cta: currentPlan === "free" ? "Plan actuel" : "Rester gratuit",
              disabled: currentPlan === "free",
              current: currentPlan === "free",
            }}
            onClick={() => navigate("/recipes/new")}
            loading={false}
            index={0}
          />

          {/* Plans Stripe */}
          {plans.map((plan, i) => {
            const isCurrent = currentPlan === plan.id
            const isPopular = plan.id === "essential"
            return (
              <PlanCard
                key={plan.id}
                plan={{
                  ...plan,
                  price: plan.id === "essential" ? "3€" : "5€",
                  period: "/mois",
                  cta: isCurrent ? "Plan actuel" : `Choisir ${plan.name}`,
                  disabled: isCurrent || !plan.available,
                  current: isCurrent,
                  popular: isPopular,
                }}
                onClick={() => handleCheckout(plan.id)}
                loading={checkoutLoading === plan.id}
                index={i + 1}
              />
            )
          })}
        </div>
      )}

      {/* FAQ / notes */}
      <motion.div
        className="mt-16 text-center text-sm text-muted-foreground max-w-2xl mx-auto space-y-2"
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 0.4 }}
      >
        <p>
          🔒 Les paiements sont traités de façon sécurisée par Stripe. Nous ne stockons
          aucune information bancaire.
        </p>
        <p>
          Tu peux changer de plan ou annuler à tout moment depuis ton profil.
        </p>
      </motion.div>
    </div>
  )
}

// ---------------------------------------------------------------------------

interface PlanCardProps {
  plan: {
    id: string
    name: string
    description: string
    features: string[]
    price: string
    period?: string
    cta: string
    disabled: boolean
    current: boolean
    popular?: boolean
  }
  onClick: () => void
  loading: boolean
  index: number
}

function PlanCard({ plan, onClick, loading, index }: PlanCardProps) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 24 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: index * 0.1, duration: 0.4, ease: [0.22, 1, 0.36, 1] }}
      className={`relative rounded-2xl p-6 md:p-8 flex flex-col ${
        plan.popular
          ? "bg-gradient-to-br from-orange-500 to-amber-500 text-white shadow-2xl shadow-orange-500/30 md:-translate-y-4"
          : "bg-card/80 backdrop-blur-sm border border-border/60 shadow-sm"
      }`}
    >
      {plan.popular && (
        <div className="absolute -top-3 left-1/2 -translate-x-1/2">
          <Badge className="bg-white text-orange-600 border-0 shadow-md px-3 py-1">
            <Sparkles className="h-3 w-3 mr-1" />
            Le plus populaire
          </Badge>
        </div>
      )}

      {plan.current && (
        <div className="absolute top-4 right-4">
          <Badge
            variant="secondary"
            className={
              plan.popular
                ? "bg-white/20 text-white border-0 backdrop-blur-sm"
                : "bg-emerald-50 text-emerald-700 border border-emerald-200"
            }
          >
            Plan actuel
          </Badge>
        </div>
      )}

      <h3
        className={`text-xl font-bold ${plan.popular ? "text-white" : "text-foreground"}`}
      >
        {plan.name}
      </h3>
      <p
        className={`text-sm mt-1 ${plan.popular ? "text-white/80" : "text-muted-foreground"}`}
      >
        {plan.description}
      </p>

      <div className="mt-6 flex items-baseline gap-1">
        <span
          className={`text-5xl font-bold tracking-tight ${plan.popular ? "text-white" : ""}`}
        >
          {plan.price}
        </span>
        {plan.period && (
          <span
            className={`text-sm ${plan.popular ? "text-white/70" : "text-muted-foreground"}`}
          >
            {plan.period}
          </span>
        )}
      </div>

      <ul className="mt-6 space-y-3 flex-1">
        {plan.features.map((feature) => (
          <li key={feature} className="flex gap-2 text-sm">
            <Check
              className={`h-5 w-5 shrink-0 ${
                plan.popular ? "text-white" : "text-emerald-500"
              }`}
              strokeWidth={2.5}
            />
            <span className={plan.popular ? "text-white/90" : "text-foreground/90"}>
              {feature}
            </span>
          </li>
        ))}
      </ul>

      <Button
        onClick={onClick}
        disabled={plan.disabled || loading}
        className={`mt-8 w-full h-12 rounded-full font-semibold transition-all ${
          plan.popular
            ? "bg-white text-orange-600 hover:bg-white/90 shadow-lg"
            : plan.current
              ? "bg-muted text-muted-foreground cursor-default hover:bg-muted"
              : "bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600 text-white shadow-md hover:shadow-lg"
        }`}
      >
        {loading ? (
          <>
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            Redirection…
          </>
        ) : (
          <>
            {plan.cta}
            {!plan.disabled && !plan.popular && <Zap className="ml-2 h-4 w-4" />}
          </>
        )}
      </Button>
    </motion.div>
  )
}
