"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 { Input } from "@/components/ui/input"
import { Search, Plus, Clock, Utensils, Heart, Share2, ArrowUpRight } from "lucide-react"
import { motion } from "framer-motion"
import { CookingLoader } from "@/components/illustrations/CookingLoader"
import { KitchenIllustration } from "@/components/illustrations/KitchenIllustration"
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"

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()
        setRecipes(data)
      } 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="dark:from-slate-950 dark:to-slate-900">

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

      <div className="flex flex-col mx-4 md:mx-4 sm:flex-row sm:items-center sm:justify-between mb-6 mt-6">
        <Tabs defaultValue="all" className="w-full sm:w-auto" onValueChange={setActiveFilter}>
          <TabsList className="grid grid-cols-4 w-full sm:w-auto">
            <TabsTrigger value="all">Toutes</TabsTrigger>
            <TabsTrigger value="easy">Faciles</TabsTrigger>
            <TabsTrigger value="quick">Rapides</TabsTrigger>
            <TabsTrigger value="vegetarian">Végé</TabsTrigger>
          </TabsList>
        </Tabs>

        <Button
          onClick={handleCreateRecipe}
          className="mt-4 sm:mt-0 bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600 text-white cursor-pointer"
        >
          <Plus className="mr-2 h-4 w-4" />
          Nouvelle recette
        </Button>
      </div>

      {loading ? (
        <CookingLoader />
      ) : (
        <>
          {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-8 right-8 sm:hidden">
        <motion.div initial={{ scale: 0.8, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} transition={{ delay: 0.2 }}>
          <Button
            onClick={handleCreateRecipe}
            className="h-14 w-14 rounded-full shadow-lg bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600"
            size="icon"
          >
            <Plus className="h-6 w-6" />
          </Button>
        </motion.div>
      </div>
    </div>
  )
}

interface RecipeCardProps {
  recipe: Recipe
  index: number
}

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

  return (
    <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: index * 0.05 }}>
      <Card className="overflow-hidden h-full border-none shadow-md hover:shadow-lg transition-all duration-300">
        <div
          className="relative aspect-video w-full overflow-hidden cursor-pointer"
          onClick={() => navigate(`/recipes/${recipe.id}`)}
        >
          <img
            src={recipe.imageUrl || "/placeholder.svg?height=200&width=400"}
            alt={recipe.title}
            className="h-full w-full object-cover transition-transform hover:scale-105 duration-500"
          />
          <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent flex items-end">
            <div className="p-4 text-white">
              <h3 className="font-bold text-lg">{recipe.title}</h3>
              <p className="text-sm opacity-90 line-clamp-1">{recipe.description || "Aucune description disponible"}</p>
            </div>
          </div>

          <div className="absolute top-2 right-2 flex gap-1">
            {recipe.difficulty === "Facile" && (
              <Badge variant="secondary" className="bg-green-500/80 text-white hover:bg-green-600/80">
                Facile
              </Badge>
            )}
            {recipe.difficulty === "Moyen" && (
              <Badge variant="secondary" className="bg-yellow-500/80 text-white hover:bg-yellow-600/80">
                Moyen
              </Badge>
            )}
            {recipe.difficulty === "Difficile" && (
              <Badge variant="secondary" className="bg-red-500/80 text-white hover:bg-red-600/80">
                Difficile
              </Badge>
            )}
            {(recipe.preparationTime || 0) <= 30 && (
              <Badge variant="secondary" className="bg-blue-500/80 text-white hover:bg-blue-600/80">
                Rapide
              </Badge>
            )}
          </div>
        </div>

        <CardContent className="p-4">
          <div className="flex flex-wrap gap-1 mb-3">
            {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">
            {recipe.preparationTime && (
              <div className="flex items-center">
                <Clock className="h-3 w-3 mr-1" />
                <span>{recipe.preparationTime} 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">
          <Button
            variant="outline"
            size="sm"
            className="rounded-full"
            onClick={() => navigate(`/recipes/${recipe.id}`)}
          >
            Voir la recette
            <ArrowUpRight className="ml-1 h-3 w-3" />
          </Button>

          <div className="flex gap-1">
            <Button variant="ghost" size="icon" className="h-8 w-8 rounded-full">
              <Heart className="h-4 w-4" />
            </Button>
            <Button variant="ghost" size="icon" className="h-8 w-8 rounded-full">
              <Share2 className="h-4 w-4" />
            </Button>
          </div>
        </CardFooter>
      </Card>
    </motion.div>
  )
}

