import { useEffect, useState } from "react"
import { Link, useNavigate } from "react-router-dom"
import { motion } from "framer-motion"
import { CheckCircle2, Sparkles, ArrowRight, ChefHat } from "lucide-react"
import { Button } from "@/components/ui/button"
import stripeService, { type SubscriptionStatus } from "@/api/stripe"

export default function CheckoutSuccess() {
  const navigate = useNavigate()
  const [subscription, setSubscription] = useState<SubscriptionStatus | null>(null)
  const [polling, setPolling] = useState(true)

  // Stratégie en 2 temps :
  // 1. Essaye d'abord un sync direct depuis Stripe (instantané, fiable)
  // 2. Si ça échoue, poll /stripe/subscription jusqu'à ce que le webhook
  //    ait activé l'abo (max 10 × 1.5s)
  useEffect(() => {
    let cancelled = false

    const hydrate = async () => {
      // Tentative #1 : sync immédiat
      try {
        const synced = await stripeService.syncSubscription()
        if (cancelled) return
        if (synced.hasActiveSubscription || synced.plan !== "free") {
          setSubscription(synced)
          setPolling(false)
          return
        }
      } catch {
        /* on tombe dans le polling */
      }

      // Tentative #2 : polling (si le sync n'a rien trouvé, ce qui peut
      // arriver si Stripe n'a pas encore flushé la subscription)
      let attempts = 0
      const maxAttempts = 10
      const interval = setInterval(async () => {
        attempts++
        try {
          const sub = await stripeService.getSubscription()
          if (cancelled) {
            clearInterval(interval)
            return
          }
          setSubscription(sub)
          if (sub.hasActiveSubscription || attempts >= maxAttempts) {
            clearInterval(interval)
            setPolling(false)
          }
        } catch {
          if (attempts >= maxAttempts) {
            clearInterval(interval)
            setPolling(false)
          }
        }
      }, 1500)
    }

    hydrate()
    return () => {
      cancelled = true
    }
  }, [])

  const planName =
    subscription?.plan === "essential"
      ? "Essentiel"
      : subscription?.plan === "premium"
        ? "Premium"
        : "Premium"

  return (
    <div className="mx-auto max-w-2xl px-4 py-12 md:py-20 text-center">
      {/* Icône succès animée */}
      <motion.div
        className="relative mx-auto mb-8 flex h-28 w-28 items-center justify-center"
        initial={{ scale: 0, rotate: -180 }}
        animate={{ scale: 1, rotate: 0 }}
        transition={{ type: "spring", stiffness: 200, damping: 15 }}
      >
        {/* Halo */}
        <motion.div
          className="absolute inset-0 rounded-full bg-gradient-to-br from-emerald-300/50 to-emerald-500/30 blur-2xl"
          animate={{ scale: [1, 1.2, 1], opacity: [0.6, 1, 0.6] }}
          transition={{ duration: 2.5, repeat: Infinity }}
        />
        {/* Étincelles */}
        {[0, 1, 2, 3].map((i) => (
          <motion.div
            key={i}
            className="absolute"
            style={{
              top: ["0%", "0%", "100%", "100%"][i],
              left: ["0%", "100%", "0%", "100%"][i],
            }}
            animate={{
              scale: [0, 1, 0],
              opacity: [0, 1, 0],
            }}
            transition={{
              duration: 2,
              repeat: Infinity,
              delay: i * 0.3,
            }}
          >
            <Sparkles className="h-4 w-4 text-amber-400" />
          </motion.div>
        ))}
        {/* Check principal */}
        <div className="relative z-10 flex h-24 w-24 items-center justify-center rounded-full bg-gradient-to-br from-emerald-400 to-emerald-600 text-white shadow-2xl shadow-emerald-500/40 ring-4 ring-white dark:ring-slate-900">
          <CheckCircle2 className="h-14 w-14" strokeWidth={2} />
        </div>
      </motion.div>

      <motion.div
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.3 }}
      >
        <h1 className="text-3xl md:text-4xl font-bold tracking-tight mb-2">
          Bienvenue dans{" "}
          <span className="text-warm-gradient">{planName}</span>
          {" "}
          <Sparkles className="inline h-6 w-6 md:h-8 md:w-8 text-amber-400" />
        </h1>
        <p className="text-muted-foreground text-base md:text-lg max-w-md mx-auto mt-3">
          Ton abonnement est actif. Tu peux dès maintenant profiter de toutes les
          fonctionnalités premium.
        </p>
      </motion.div>

      {polling && !subscription?.hasActiveSubscription && (
        <motion.p
          className="mt-6 text-sm text-muted-foreground"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.8 }}
        >
          <span className="animate-pulse">Activation de ton abonnement…</span>
        </motion.p>
      )}

      <motion.div
        className="mt-10 flex flex-col sm:flex-row gap-3 justify-center"
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.5 }}
      >
        <Link to="/recipes/new">
          <Button
            size="lg"
            className="w-full sm:w-auto h-12 px-6 rounded-full bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600 text-white shadow-md shadow-orange-500/25 hover:shadow-lg hover:shadow-orange-500/40 transition-all font-semibold group"
          >
            <ChefHat className="mr-2 h-5 w-5" />
            Créer ma première recette
            <ArrowRight className="ml-2 h-4 w-4 transition-transform group-hover:translate-x-1" />
          </Button>
        </Link>
        <Button
          size="lg"
          variant="outline"
          className="w-full sm:w-auto h-12 px-6 rounded-full"
          onClick={() => navigate("/profile")}
        >
          Gérer mon compte
        </Button>
      </motion.div>

      <motion.p
        className="mt-12 text-xs text-muted-foreground"
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 0.8 }}
      >
        Un reçu a été envoyé à ton adresse email.
      </motion.p>
    </div>
  )
}
