"use client"

import { useState, useEffect, useRef } from "react"
import { useParams, useNavigate } from "react-router-dom"
import { recipeService, type Recipe } from "@/api/recipe"
import { Button } from "@/components/ui/button"
import {
  Clock,
  Users,
  ChefHat,
  Heart,
  Share2,
  ArrowLeft,
  Trash2,
  Edit,
  Printer,
  CheckCircle2,
  Timer,
  ChevronUp,
} from "lucide-react"
import { motion, AnimatePresence } from "framer-motion"
import { RecipeDetailLoader } from "@/components/illustrations/RecipeDetailLoader"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent } from "@/components/ui/card"
import { Checkbox } from "@/components/ui/checkbox"

export default function RecipeDetail() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const contentRef = useRef<HTMLDivElement>(null)

  const [recipe, setRecipe] = useState<Recipe | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState("")
  const [isFavorite, setIsFavorite] = useState(false)
  const [addingToFavorites, setAddingToFavorites] = useState(false)
  const [checkedIngredients, setCheckedIngredients] = useState<Set<number>>(new Set())
  const [checkedSteps, setCheckedSteps] = useState<Set<number>>(new Set())
  const [showScrollTop, setShowScrollTop] = useState(false)

  useEffect(() => {
    const fetchRecipeDetails = async () => {
      if (!id) return

      try {
        setLoading(true)

        // ✅ GET RECIPE DETAILS
        const recipeData = await recipeService.getRecipeById(id)

        // Optionnel : conversion ingrédients / instructions si nécessaire
        let ingredients = recipeData.ingredients
        if (typeof ingredients === "string") {
          ingredients = ingredients.split("\n").filter((item) => item.trim() !== "")
        }

        // Correction: déclarer la variable instructions
        let instructions: string[] = []
        if (recipeData.generatedRecipe) {
          instructions = recipeData.generatedRecipe.split("\n").filter((item) => item.trim() !== "")
        }

        setRecipe({
          ...recipeData,
          ingredients,
          instructions, // Ajouter instructions au recipe
        })

        // ✅ GET FAVORITE RECIPES & CHECK IF FAVORITE
        try {
          const favorites = await recipeService.getFavoriteRecipes()
          setIsFavorite(favorites.some((fav) => fav.id === id))
        } catch (favError) {
          // Ignorer les erreurs de favoris pour ne pas bloquer l'affichage
          console.log("Impossible de vérifier les favoris:", favError)
        }
      } catch (err) {
        console.error(err)
        setError("Impossible de charger les détails de la recette")
      } finally {
        setLoading(false)
      }
    }

    fetchRecipeDetails()

    // Setup scroll listener
    const handleScroll = () => {
      if (window.scrollY > 300) {
        setShowScrollTop(true)
      } else {
        setShowScrollTop(false)
      }
    }

    window.addEventListener("scroll", handleScroll)
    return () => window.removeEventListener("scroll", handleScroll)
  }, [id])

  const handleToggleFavorite = async () => {
    if (!id || !recipe) return

    try {
      setAddingToFavorites(true)

      if (isFavorite) {
        // ✅ REMOVE FROM FAVORITES
        await recipeService.removeFromFavorites(id)
        setIsFavorite(false)
      } else {
        // ✅ ADD TO FAVORITES
        await recipeService.addToFavorites(id)
        setIsFavorite(true)
      }
    } catch (err) {
      console.error("Erreur lors de la modification des favoris:", err)
      // Ne pas afficher d'erreur à l'utilisateur pour cette fonctionnalité
    } finally {
      setAddingToFavorites(false)
    }
  }

  const handleDeleteRecipe = async () => {
    if (!id) return
    if (!window.confirm("Êtes-vous sûr de vouloir supprimer cette recette ?")) return

    try {
      // ✅ DELETE RECIPE
      await recipeService.deleteRecipe(id)
      navigate("/recipes")
    } catch (err) {
      console.error("Erreur lors de la suppression:", err)
      // Optionnel: afficher un message d'erreur à l'utilisateur
    }
  }

  const handleShare = () => {
    if (!recipe) return

    if (navigator.share) {
      navigator.share({
        title: recipe.title,
        text: recipe.description || "Découvrez cette recette !",
        url: window.location.href,
      })
    } else {
      navigator.clipboard.writeText(window.location.href)
      alert("Lien copié dans le presse-papier !")
    }
  }

  const handlePrint = () => {
    window.print()
  }

  const toggleIngredient = (index: number) => {
    const newChecked = new Set(checkedIngredients)
    if (newChecked.has(index)) {
      newChecked.delete(index)
    } else {
      newChecked.add(index)
    }
    setCheckedIngredients(newChecked)
  }

  const toggleStep = (index: number) => {
    const newChecked = new Set(checkedSteps)
    if (newChecked.has(index)) {
      newChecked.delete(index)
    } else {
      newChecked.add(index)
    }
    setCheckedSteps(newChecked)
  }

  const scrollToTop = () => {
    window.scrollTo({ top: 0, behavior: "smooth" })
  }

  // ========================================
  // === LOADING & ERROR STATES ============
  // ========================================
  if (loading) {
    return <RecipeDetailLoader />
  }

  if (error || !recipe) {
    return (
      <div className="rounded-md bg-red-50 p-6 text-center text-red-700 dark:bg-red-900/50 dark:text-red-200">
        <h2 className="text-xl font-bold">Erreur</h2>
        <p>{error || "Recette introuvable"}</p>
        <Button variant="outline" className="mt-4" onClick={() => navigate("/recipes")}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Retour aux recettes
        </Button>
      </div>
    )
  }

  // Calculate total time
  const totalTime = (recipe.preparationTime || 0) + (recipe.cookingTime || 0)

  // ========================================
  // === MAIN COMPONENT =====================
  // ========================================
  return (
    <div className="min-h-screen bg-gradient-to-b from-amber-50 to-orange-50 dark:from-slate-950 dark:to-slate-900 pb-16">
      {/* Header */}
      <header className="sticky top-0 z-10 bg-white/80 dark:bg-slate-900/80 backdrop-blur-md border-b border-slate-200 dark:border-slate-800 print:hidden">
        <div className="container px-4 py-3">
          <div className="flex items-center justify-between">
            <Button variant="ghost" className="flex items-center gap-2" onClick={() => navigate("/recipes")}>
              <ArrowLeft className="h-4 w-4" />
              Retour aux recettes
            </Button>

            <div className="flex gap-2">
              <Button variant="ghost" size="icon" className="rounded-full" onClick={handlePrint}>
                <Printer className="h-4 w-4" />
              </Button>

              <Button variant="ghost" size="icon" className="rounded-full" onClick={handleShare}>
                <Share2 className="h-4 w-4" />
              </Button>

              <Button
                variant={isFavorite ? "default" : "ghost"}
                size="icon"
                className={`rounded-full ${isFavorite ? "bg-red-500 hover:bg-red-600 text-white" : ""}`}
                onClick={handleToggleFavorite}
                disabled={addingToFavorites}
              >
                <Heart className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </div>
      </header>

      {/* Main content */}
      <main className="container px-4 py-6" ref={contentRef}>
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.5 }}>
          {/* Recipe Hero */}
          <div className="relative rounded-xl overflow-hidden mb-8">
            <img
              src={recipe.imageUrl || "/placeholder.svg?height=400&width=800"}
              alt={recipe.title}
              className="w-full h-[300px] md:h-[400px] object-cover"
            />
            <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/30 to-transparent flex flex-col justify-end p-6">
              <div className="flex flex-wrap gap-2 mb-3">
                {recipe.tags?.map((tag) => (
                  <Badge key={tag} variant="secondary" className="bg-white/20 text-white border-none">
                    {tag}
                  </Badge>
                ))}
              </div>
              <h1 className="text-3xl md:text-4xl font-bold text-white mb-2">{recipe.title}</h1>
              <p className="text-white/80 max-w-2xl">{recipe.description || "Aucune description disponible"}</p>
            </div>
          </div>

          {/* Recipe Info Cards */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
            <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-none shadow-sm">
              <CardContent className="flex flex-col items-center justify-center p-4">
                <Clock className="h-6 w-6 text-orange-500 mb-2" />
                <span className="text-sm text-muted-foreground">Préparation</span>
                <span className="text-lg font-bold">{recipe.preparationTime || 0} min</span>
              </CardContent>
            </Card>

            <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-none shadow-sm">
              <CardContent className="flex flex-col items-center justify-center p-4">
                <Timer className="h-6 w-6 text-orange-500 mb-2" />
                <span className="text-sm text-muted-foreground">Cuisson</span>
                <span className="text-lg font-bold">{recipe.cookingTime || 0} min</span>
              </CardContent>
            </Card>

            <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-none shadow-sm">
              <CardContent className="flex flex-col items-center justify-center p-4">
                <Users className="h-6 w-6 text-orange-500 mb-2" />
                <span className="text-sm text-muted-foreground">Portions</span>
                <span className="text-lg font-bold">{recipe.servings || "-"}</span>
              </CardContent>
            </Card>

            <Card className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm border-none shadow-sm">
              <CardContent className="flex flex-col items-center justify-center p-4">
                <ChefHat className="h-6 w-6 text-orange-500 mb-2" />
                <span className="text-sm text-muted-foreground">Difficulté</span>
                <span className="text-lg font-bold capitalize">{recipe.difficulty || "-"}</span>
              </CardContent>
            </Card>
          </div>

          {/* Recipe Content */}
          <div className="grid md:grid-cols-3 gap-8">
            {/* Ingredients */}
            <div className="md:col-span-1">
              <Card className="bg-white/90 dark:bg-slate-800/90 backdrop-blur-sm border-none shadow-sm sticky top-[85px]">
                <CardContent className="p-6">
                  <h2 className="text-xl font-bold mb-4 flex items-center">
                    <span className="bg-orange-100 dark:bg-orange-900/30 text-orange-800 dark:text-orange-300 w-8 h-8 rounded-full flex items-center justify-center mr-2">
                      1
                    </span>
                    Ingrédients
                  </h2>

                  {totalTime > 0 && (
                    <div className="mb-4 p-3 bg-orange-50 dark:bg-orange-900/20 rounded-lg">
                      <p className="text-sm flex items-center">
                        <Clock className="h-4 w-4 mr-2 text-orange-500" />
                        Temps total: <span className="font-bold ml-1">{totalTime} min</span>
                      </p>
                    </div>
                  )}

                  <ul className="space-y-2">
                    {Array.isArray(recipe.ingredients) ? (
                      recipe.ingredients.map((ingredient, index) => (
                        <li key={index} className="flex items-center">
                          <Checkbox
                            id={`ingredient-${index}`}
                            checked={checkedIngredients.has(index)}
                            onCheckedChange={() => toggleIngredient(index)}
                            className="mr-2 data-[state=checked]:bg-orange-500 data-[state=checked]:border-orange-500"
                          />
                          <label
                            htmlFor={`ingredient-${index}`}
                            className={`flex-1 cursor-pointer ${checkedIngredients.has(index) ? "line-through text-muted-foreground" : ""}`}
                          >
                            {ingredient}
                          </label>
                        </li>
                      ))
                    ) : (
                      <li className="flex items-center">
                        <Checkbox
                          id="ingredient-single"
                          checked={checkedIngredients.has(0)}
                          onCheckedChange={() => toggleIngredient(0)}
                          className="mr-2 data-[state=checked]:bg-orange-500 data-[state=checked]:border-orange-500"
                        />
                        <label
                          htmlFor="ingredient-single"
                          className={`flex-1 cursor-pointer ${checkedIngredients.has(0) ? "line-through text-muted-foreground" : ""}`}
                        >
                          {recipe.ingredients}
                        </label>
                      </li>
                    )}
                  </ul>
                </CardContent>
              </Card>
            </div>

            {/* Instructions */}
            <div className="md:col-span-2">
              <Card className="bg-white/90 dark:bg-slate-800/90 backdrop-blur-sm border-none shadow-sm">
                <CardContent className="p-6">
                  <h2 className="text-xl font-bold mb-6 flex items-center">
                    <span className="bg-orange-100 dark:bg-orange-900/30 text-orange-800 dark:text-orange-300 w-8 h-8 rounded-full flex items-center justify-center mr-2">
                      2
                    </span>
                    Instructions
                  </h2>

                  <ol className="space-y-6">
                    {recipe.instructions && recipe.instructions.length > 0 ? (
                      recipe.instructions.map((instruction, index) => (
                        <li key={index} className="flex">
                          <Checkbox
                            id={`step-${index}`}
                            checked={checkedSteps.has(index)}
                            onCheckedChange={() => toggleStep(index)}
                            className="mr-3 mt-1 data-[state=checked]:bg-orange-500 data-[state=checked]:border-orange-500"
                          />
                          <div className="flex-1">
                            <label
                              htmlFor={`step-${index}`}
                              className={`flex items-center font-medium mb-2 cursor-pointer ${checkedSteps.has(index) ? "line-through text-muted-foreground" : ""}`}
                            >
                              Étape {index + 1}
                              {checkedSteps.has(index) && <CheckCircle2 className="ml-2 h-4 w-4 text-green-500" />}
                            </label>
                            <p className={checkedSteps.has(index) ? "text-muted-foreground" : ""}>{instruction}</p>
                          </div>
                        </li>
                      ))
                    ) : (
                      <li className="flex">
                        <Checkbox
                          id="step-single"
                          checked={checkedSteps.has(0)}
                          onCheckedChange={() => toggleStep(0)}
                          className="mr-3 mt-1 data-[state=checked]:bg-orange-500 data-[state=checked]:border-orange-500"
                        />
                        <div className="flex-1">
                          <label
                            htmlFor="step-single"
                            className={`flex items-center font-medium mb-2 cursor-pointer ${checkedSteps.has(0) ? "line-through text-muted-foreground" : ""}`}
                          >
                            Instructions
                            {checkedSteps.has(0) && <CheckCircle2 className="ml-2 h-4 w-4 text-green-500" />}
                          </label>
                          <p className={checkedSteps.has(0) ? "text-muted-foreground" : ""}>{recipe.generatedRecipe}</p>
                        </div>
                      </li>
                    )}
                  </ol>
                </CardContent>
              </Card>
            </div>
          </div>

          {/* Admin Actions */}
          <div className="mt-8 flex justify-end gap-2 print:hidden">
            <Button variant="outline" onClick={() => navigate(`/recipes/edit/${id}`)}>
              <Edit className="mr-2 h-4 w-4" />
              Modifier
            </Button>

            <Button variant="destructive" onClick={handleDeleteRecipe}>
              <Trash2 className="mr-2 h-4 w-4" />
              Supprimer
            </Button>
          </div>
        </motion.div>
      </main>

      {/* Scroll to top button */}
      <AnimatePresence>
        {showScrollTop && (
          <motion.div
            className="fixed bottom-8 right-8 print:hidden"
            initial={{ opacity: 0, scale: 0.8 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.8 }}
            transition={{ duration: 0.2 }}
          >
            <Button
              onClick={scrollToTop}
              className="h-12 w-12 rounded-full shadow-lg bg-white dark:bg-slate-800"
              size="icon"
            >
              <ChevronUp className="h-6 w-6" />
            </Button>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  )
}

