"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { useNavigate } from "react-router-dom"
import { recipeService, type Recipe } from "@/api/recipe"
import { Button } from "@/components/ui/button"
import { Plus, Clock, Utensils, Heart, Share2, ArrowUpRight } from "lucide-react"
import { motion } from "framer-motion"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardFooter } from "@/components/ui/card"
import { EmptyRecipes } from "@/components/illustrations/EmptyRecipes"
import { RecipeListSkeleton } from "@/components/recipe-card-skeleton"

export default function RecipeList() {
  const navigate = useNavigate()
  const [recipes, setRecipes] = useState<Recipe[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState("")
  const [searchQuery, setSearchQuery] = useState("")
  const [activeFilter, setActiveFilter] = useState("all")

  useEffect(() => {
    const fetchRecipes = async () => {
      try {
        setLoading(true)
        const data = await recipeService.getRecipes()

        // Traiter les données pour s'assurer que les propriétés sont correctement formatées
        const processedData = data.map(recipe => {
          // Convertir les difficultés pour correspondre aux filtres
          let normalizedDifficulty = recipe.difficulty;
          if (recipe.difficulty === "facile") normalizedDifficulty = "Facile";
          if (recipe.difficulty === "moyen") normalizedDifficulty = "Moyen";
          if (recipe.difficulty === "difficile") normalizedDifficulty = "Difficile";

          return {
            ...recipe,
            difficulty: normalizedDifficulty,
            // Ajouter des tags par défaut si nécessaire
            tags: recipe.tags || []
          };
        });

        setRecipes(processedData);
      } catch (err) {
        setError("Impossible de charger les recettes")
        console.error(err)
      } finally {
        setLoading(false)
      }
    }

    fetchRecipes()
  }, [])

  const handleSearch = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!searchQuery.trim()) {
      const data = await recipeService.getRecipes()
      setRecipes(data)
      return
    }

    try {
      setLoading(true)
      const results = await recipeService.getRecipes()
      setRecipes(results)
    } catch (err) {
      setError("Erreur lors de la recherche")
      console.error(err)
    } finally {
      setLoading(false)
    }
  }

  const handleCreateRecipe = () => {
    navigate("/recipes/new")
  }

  // Filter recipes based on the active filter
  const filteredRecipes = recipes.filter((recipe) => {
    if (activeFilter === "all") return true
    if (activeFilter === "easy" && recipe.difficulty === "Facile") return true
    if (activeFilter === "quick" && (recipe.preparationTime || 0) <= 30) return true
    if (activeFilter === "vegetarian" && recipe.tags?.includes("Végétarien")) return true
    return false
  })

  return (
    <div className="min-h-[calc(100vh-4rem)]">
      {/* Header de page avec titre */}
      <div className="mx-4 md:mx-8 mt-8 mb-6">
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.4 }}
        >
          <h1 className="text-3xl md:text-4xl font-bold tracking-tight">
            Mes recettes
          </h1>
          <p className="text-muted-foreground mt-1">
            {loading
              ? "Chargement de votre collection…"
              : recipes.length > 0
                ? `${recipes.length} recette${recipes.length > 1 ? "s" : ""} dans votre carnet`
                : "Commencez votre collection dès maintenant"}
          </p>
        </motion.div>
      </div>

      {/* Erreur */}
      {error && (
        <motion.div
          className="mx-4 md:mx-8 rounded-xl bg-red-50 p-4 text-red-700 dark:bg-red-950/40 dark:text-red-200 mb-6 border border-red-100 dark:border-red-900/40"
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
        >
          {error}
        </motion.div>
      )}

      {/* Barre filtres + CTA */}
      <div className="flex flex-col mx-4 md:mx-8 sm:flex-row sm:items-center sm:justify-between mb-6 gap-3">
        <Tabs defaultValue="all" className="w-full sm:w-auto" onValueChange={setActiveFilter}>
          <TabsList className="grid grid-cols-4 w-full sm:w-auto bg-muted/60 backdrop-blur-sm">
            <TabsTrigger value="all" className="data-[state=active]:bg-white dark:data-[state=active]:bg-slate-800 data-[state=active]:shadow-sm transition-all">
              Toutes
            </TabsTrigger>
            <TabsTrigger value="easy" className="data-[state=active]:bg-white dark:data-[state=active]:bg-slate-800 data-[state=active]:shadow-sm transition-all">
              Faciles
            </TabsTrigger>
            <TabsTrigger value="quick" className="data-[state=active]:bg-white dark:data-[state=active]:bg-slate-800 data-[state=active]:shadow-sm transition-all">
              Rapides
            </TabsTrigger>
            <TabsTrigger value="vegetarian" className="data-[state=active]:bg-white dark:data-[state=active]:bg-slate-800 data-[state=active]:shadow-sm transition-all">
              Végé
            </TabsTrigger>
          </TabsList>
        </Tabs>
        {filteredRecipes.length !== 0 && (
          <Button
            onClick={handleCreateRecipe}
            className="hidden sm:inline-flex 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 hover:shadow-orange-500/25 transition-all cursor-pointer"
          >
            <Plus className="mr-2 h-4 w-4" />
            Nouvelle recette
          </Button>
        )}
      </div>

      {loading ? (
        <RecipeListSkeleton count={6} />
      ) : (
        <>
          {filteredRecipes.length === 0 ? (
            <EmptyRecipes onCreateRecipe={handleCreateRecipe} />
          ) : (
            <motion.div
              className="grid gap-6 my-6 mx-4 sm:grid-cols-2 lg:grid-cols-3"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ staggerChildren: 0.1 }}
            >
              {filteredRecipes.map((recipe, index) => (
                <RecipeCard key={recipe.id} recipe={recipe} index={index} />
              ))}
            </motion.div>
          )}
        </>
      )}

      {/* Floating action button (mobile only) */}
      <div className="fixed bottom-6 right-6 sm:hidden z-30 safe-pb">
        <motion.div
          initial={{ scale: 0, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          transition={{ delay: 0.3, type: "spring", stiffness: 260, damping: 20 }}
          whileTap={{ scale: 0.9 }}
        >
          <Button
            onClick={handleCreateRecipe}
            className="h-14 w-14 rounded-full shadow-xl shadow-orange-500/30 bg-gradient-to-br from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600 animate-glow-pulse"
            size="icon"
            aria-label="Créer une nouvelle recette"
          >
            <Plus className="h-6 w-6" strokeWidth={2.5} />
          </Button>
        </motion.div>
      </div>
    </div>
  )
}

interface RecipeCardProps {
  recipe: Recipe
  index: number
}

function RecipeCard({ recipe, index }: RecipeCardProps) {
  const navigate = useNavigate()

  // Normaliser la difficulté pour l'affichage des badges
  const difficultyClass = {
    "Facile": "bg-green-500/80 text-white hover:bg-green-600/80",
    "facile": "bg-green-500/80 text-white hover:bg-green-600/80",
    "Moyen": "bg-yellow-500/80 text-white hover:bg-yellow-600/80",
    "moyen": "bg-yellow-500/80 text-white hover:bg-yellow-600/80",
    "Difficile": "bg-red-500/80 text-white hover:bg-red-600/80",
    "difficile": "bg-red-500/80 text-white hover:bg-red-600/80"
  }[recipe.difficulty || ""] || "bg-gray-500/80 text-white hover:bg-gray-600/80";

  return (
    <motion.div
      initial={{ opacity: 0, y: 24 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: index * 0.06, duration: 0.4, ease: [0.22, 1, 0.36, 1] }}
      whileHover={{ y: -4 }}
      className="group"
    >
      <Card className="overflow-hidden h-full border border-transparent bg-card/60 backdrop-blur-sm shadow-sm hover:shadow-2xl hover:border-orange-200/60 dark:hover:border-orange-800/40 transition-all duration-500 rounded-2xl">
        <div
          className="relative aspect-video w-full overflow-hidden cursor-pointer"
          onClick={() => navigate(`/recipes/${recipe.id}`)}
        >
          {/* Image avec zoom subtil */}
          <img
            src={recipe.imageUrl || "/placeholder.svg?height=200&width=400"}
            alt={recipe.title}
            loading="lazy"
            className="h-full w-full object-cover transition-transform duration-[800ms] ease-out group-hover:scale-110"
          />

          {/* Dégradé plus prononcé pour la lisibilité */}
          <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent" />

          {/* Brillance au hover */}
          <div className="absolute inset-0 bg-gradient-to-tr from-transparent via-white/0 to-white/0 group-hover:to-white/10 transition-all duration-700" />

          {/* Titre + description en bas */}
          <div className="absolute inset-x-0 bottom-0 p-4 text-white">
            <h3 className="font-semibold text-lg leading-tight line-clamp-1 drop-shadow-sm">
              {recipe.title}
            </h3>
            <p className="text-sm opacity-90 line-clamp-1 mt-0.5">
              {recipe.description || "Aucune description disponible"}
            </p>
          </div>

          {/* Badges flottants en haut */}
          <div className="absolute top-3 right-3 flex gap-1.5">
            {recipe.difficulty && (
              <Badge
                variant="secondary"
                className={`${difficultyClass} shadow-sm backdrop-blur-md border-0`}
              >
                {recipe.difficulty.charAt(0).toUpperCase() + recipe.difficulty.slice(1)}
              </Badge>
            )}
            {(recipe.preparationTime || 0) <= 30 && (
              <Badge
                variant="secondary"
                className="bg-blue-500/85 text-white hover:bg-blue-600/85 shadow-sm backdrop-blur-md border-0"
              >
                Rapide
              </Badge>
            )}
          </div>
        </div>

        <CardContent className="p-4">
          <div className="flex flex-wrap gap-1 mb-3">
            {recipe.tags && Array.isArray(recipe.tags) && recipe.tags.slice(0, 3).map((tag) => (
              <Badge
                key={tag}
                variant="outline"
                className="bg-orange-100 dark:bg-orange-900/30 text-orange-800 dark:text-orange-300 border-orange-200 dark:border-orange-800"
              >
                {tag}
              </Badge>
            ))}
          </div>

          <div className="flex items-center justify-between text-sm text-muted-foreground">
            <div className="flex items-center">
              <Clock className="h-3 w-3 mr-1" />
              <span>{recipe.preparationTime || 0} min</span>
            </div>

            {recipe.servings && (
              <div className="flex items-center">
                <Utensils className="h-3 w-3 mr-1" />
                <span>{recipe.servings} pers.</span>
              </div>
            )}
          </div>
        </CardContent>

        <CardFooter className="p-4 pt-0 flex justify-between items-center">
          <Button
            variant="outline"
            size="sm"
            className="rounded-full border-orange-200/70 dark:border-orange-800/50 hover:bg-orange-50 hover:text-orange-700 hover:border-orange-300 dark:hover:bg-orange-950/30 dark:hover:text-orange-300 transition-all group/btn"
            onClick={() => navigate(`/recipes/${recipe.id}`)}
          >
            Voir la recette
            <ArrowUpRight className="ml-1 h-3 w-3 transition-transform group-hover/btn:translate-x-0.5 group-hover/btn:-translate-y-0.5" />
          </Button>

          <div className="flex gap-1">
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8 rounded-full hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-950/30 transition-colors"
              onClick={(e) => e.stopPropagation()}
              aria-label="Ajouter aux favoris"
            >
              <Heart className="h-4 w-4" />
            </Button>
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8 rounded-full hover:bg-orange-50 hover:text-orange-500 dark:hover:bg-orange-950/30 transition-colors"
              onClick={(e) => e.stopPropagation()}
              aria-label="Partager"
            >
              <Share2 className="h-4 w-4" />
            </Button>
          </div>
        </CardFooter>
      </Card>
    </motion.div>
  )
}

