"use client"

import { useState, useEffect } from "react"
import { Link, useLocation } from "react-router-dom"
import { Button } from "@/components/ui/button"
import { Menu, X, LogOut, User, Home, BookOpen, Sparkles } from "lucide-react"
import { cn } from "@/lib/utils"
import { motion, AnimatePresence } from "framer-motion"
import { Logo } from "@/components/illustrations/Logo"
import useAuth from "@/hooks/useAuth"

export function Header() {
  const { isAuthenticated } = useAuth()
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)
  const [scrolled, setScrolled] = useState(false)
  const location = useLocation()

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8)
    onScroll()
    window.addEventListener("scroll", onScroll, { passive: true })
    return () => window.removeEventListener("scroll", onScroll)
  }, [])

  // Ferme le menu mobile quand on change de route
  useEffect(() => {
    setIsMobileMenuOpen(false)
  }, [location.pathname])

  const toggleMobileMenu = () => {
    setIsMobileMenuOpen(!isMobileMenuOpen)
  }

  const handleLogout = () => {
    localStorage.removeItem("token")
    setIsMobileMenuOpen(false)
    window.location.href = "/auth/login"
  }

  const navItems = [
    { name: "Accueil", path: "/", icon: Home, public: true },
    { name: "Recettes", path: "/recipes", icon: BookOpen, public: true },
    { name: "Tarifs", path: "/pricing", icon: Sparkles, public: true },
    { name: "Profil", path: "/profile", icon: User, public: false },
  ]

  const filteredNavItems = navItems.filter((item) => item.public || isAuthenticated)

  return (
    <header
      className={cn(
        "sticky top-0 z-50 w-full transition-all duration-300 safe-pt",
        scrolled
          ? "bg-white/85 dark:bg-slate-950/85 backdrop-blur-xl shadow-[0_1px_0_0_rgba(0,0,0,0.04)] dark:shadow-[0_1px_0_0_rgba(255,255,255,0.06)]"
          : "bg-white/60 dark:bg-slate-950/40 backdrop-blur-md"
      )}
    >
      <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
        <div className="flex h-16 items-center justify-between">
          <motion.div
            className="flex items-center gap-2"
            initial={{ opacity: 0, x: -8 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.4 }}
          >
            <Link to="/" className="flex items-center gap-2 group">
              <div className="transition-transform duration-500 group-hover:rotate-[-6deg]">
                <Logo size="md" showText={true} />
              </div>
            </Link>
          </motion.div>

          {/* Navigation desktop */}
          {
            isAuthenticated && (
              <nav className="hidden md:flex items-center gap-8">
                {filteredNavItems.map((item) => {
                  const isActive = location.pathname === item.path ||
                    (item.path !== "/" && location.pathname.startsWith(item.path))
                  return (
                    <Link
                      key={item.path}
                      to={item.path}
                      className={cn(
                        "relative text-sm font-medium transition-colors flex items-center gap-1.5 py-5 group",
                        isActive
                          ? "text-orange-600 dark:text-orange-400"
                          : "text-muted-foreground hover:text-foreground"
                      )}
                    >
                      <item.icon className={cn(
                        "h-4 w-4 transition-transform",
                        isActive && "scale-110"
                      )} />
                      {item.name}
                      {/* Underline animé */}
                      <span
                        className={cn(
                          "absolute inset-x-0 -bottom-px h-[2px] rounded-full bg-gradient-to-r from-orange-500 to-amber-500 transition-all duration-300",
                          isActive ? "opacity-100 scale-x-100" : "opacity-0 scale-x-50 group-hover:opacity-40"
                        )}
                      />
                    </Link>
                  )
                })}
              </nav>
            )
          }

          {/* Boutons d'authentification */}
          <div className="hidden md:flex items-center gap-4">
            {isAuthenticated ? (
              <Button
                variant="outline"
                onClick={handleLogout}
                className="border-orange-200 hover:bg-orange-50 hover:text-orange-600 dark:border-orange-800 dark:hover:bg-orange-900/20 dark:hover:text-orange-400"
              >
                <LogOut className="mr-2 h-4 w-4" />
                Déconnexion
              </Button>
            ) : (
              <>
                <Link to="/auth/login">
                  <Button variant="ghost" className="hover:text-orange-500">
                    Connexion
                  </Button>
                </Link>
                <Link to="/auth/register">
                  <Button className="bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600 text-white">
                    S'inscrire
                  </Button>
                </Link>
              </>
            )}
          </div>

          {/* Bouton menu mobile */}
          {isAuthenticated && (
            <Button variant="ghost" size="icon" className="md:hidden rounded-full" onClick={toggleMobileMenu}>
              {isMobileMenuOpen ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
            </Button>
          )}
        </div>
      </div>

      {/* Menu mobile */}
      {isAuthenticated && (
        <AnimatePresence>
          {isMobileMenuOpen && (
            <motion.div
              className="md:hidden border-b"
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: "auto" }}
              exit={{ opacity: 0, height: 0 }}
              transition={{ duration: 0.2 }}
            >
              <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-4 pb-6">
                <nav className="flex flex-col space-y-4">
                  {filteredNavItems.map((item, index) => (
                    <motion.div
                      key={item.path}
                      initial={{ opacity: 0, x: -10 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ delay: index * 0.05 }}
                    >
                      <Link
                        to={item.path}
                        className={cn(
                          "flex items-center gap-3 py-2 text-sm font-medium transition-colors hover:text-orange-500",
                          location.pathname === item.path ? "text-orange-500" : "text-muted-foreground",
                        )}
                        onClick={() => setIsMobileMenuOpen(false)}
                      >
                        <item.icon className="h-5 w-5" />
                        {item.name}
                      </Link>
                    </motion.div>
                  ))}

                  <motion.div
                    initial={{ opacity: 0, x: -10 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: filteredNavItems.length * 0.05 }}
                    className="pt-2"
                  >
                    {isAuthenticated ? (
                      <Button
                        variant="outline"
                        onClick={handleLogout}
                        className="w-full border-orange-200 hover:bg-orange-50 hover:text-orange-600 dark:border-orange-800 dark:hover:bg-orange-900/20 dark:hover:text-orange-400"
                      >
                        <LogOut className="mr-2 h-4 w-4" />
                        Déconnexion
                      </Button>
                    ) : (
                      <div className="flex flex-col space-y-2">
                        <Link to="/auth/login" onClick={() => setIsMobileMenuOpen(false)}>
                          <Button variant="ghost" className="w-full hover:text-orange-500">
                            Connexion
                          </Button>
                        </Link>
                        <Link to="/auth/register" onClick={() => setIsMobileMenuOpen(false)}>
                          <Button className="w-full bg-gradient-to-r from-orange-500 to-amber-500 hover:from-orange-600 hover:to-amber-600 text-white">
                            S'inscrire
                          </Button>
                        </Link>
                      </div>
                    )}
                  </motion.div>
                </nav>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      )}
    </header>
  )
}

