"use client";

import {
  Dialog,
  DialogPanel,
  Popover,
  PopoverButton,
  PopoverGroup,
  PopoverPanel,
} from "@headlessui/react";
import { IconChevronDown, IconMenu2, IconX } from "@tabler/icons-react";
import { useTranslations } from "next-intl";
import { useState } from "react";
import LanguageSwitcher from "@/components/ui/language-switcher";

// Import navigation data
import { blogLinks, ctaLink, mainNavLinks, servicesNav } from "@/data/links";
import { Link, usePathname } from "@/i18n/navigation";

export default function Header() {
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [servicesOpen, setServicesOpen] = useState(false);
  const [blogOpen, setBlogOpen] = useState(false);
  const [mobileServicesOpen, setMobileServicesOpen] = useState(false);
  const [mobileBlogOpen, setMobileBlogOpen] = useState(false);
  const [servicesCloseTimeout, setServicesCloseTimeout] =
    useState<NodeJS.Timeout | null>(null);
  const [blogCloseTimeout, setBlogCloseTimeout] =
    useState<NodeJS.Timeout | null>(null);
  const pathname = usePathname();
  const tCommon = useTranslations("common");
  const tNav = useTranslations("nav");

  const handleLogoClick = (e: React.MouseEvent) => {
    if (pathname === "/") {
      e.preventDefault();
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  };

  // Fonctions pour gérer l'ouverture/fermeture avec délai
  const handleServicesMouseEnter = () => {
    if (servicesCloseTimeout) {
      clearTimeout(servicesCloseTimeout);
      setServicesCloseTimeout(null);
    }
    setServicesOpen(true);
  };

  const handleServicesMouseLeave = () => {
    const timeout = setTimeout(() => {
      setServicesOpen(false);
    }, 200); // Délai de 200ms avant de fermer
    setServicesCloseTimeout(timeout);
  };

  const handleBlogMouseEnter = () => {
    if (blogCloseTimeout) {
      clearTimeout(blogCloseTimeout);
      setBlogCloseTimeout(null);
    }
    setBlogOpen(true);
  };

  const handleBlogMouseLeave = () => {
    const timeout = setTimeout(() => {
      setBlogOpen(false);
    }, 200);
    setBlogCloseTimeout(timeout);
  };

  return (
    <header className="fixed top-0 right-0 left-0 z-50 border-white/10 border-b bg-[#000]/80 backdrop-blur-md">
      <nav
        aria-label="Global"
        className="mx-auto flex max-w-7xl items-center justify-between p-4 lg:px-8"
      >
        {/* Logo */}
        <div className="flex lg:flex-1">
          <Link
            aria-label="ElevaSEO - Home"
            className="p-3"
            href="/"
            onClick={handleLogoClick}
          >
            <span className="bg-gradient-to-r from-white to-[#FD105E] bg-clip-text font-bold text-2xl text-transparent">
              ElevaSEO
            </span>
          </Link>
        </div>

        {/* Mobile menu button */}
        <div className="flex lg:hidden">
          <button
            className="inline-flex items-center justify-center rounded-md p-3 text-white"
            onClick={() => setMobileMenuOpen(true)}
            type="button"
          >
            <span className="sr-only">{tCommon("openMenu")}</span>
            <IconMenu2 aria-hidden="true" className="h-6 w-6" />
          </button>
        </div>

        {/* Desktop navigation */}
        <PopoverGroup className="hidden lg:flex lg:gap-x-8">
          {/* Services - Mega Menu */}
          <Popover
            className="relative"
            onMouseEnter={handleServicesMouseEnter}
            onMouseLeave={handleServicesMouseLeave}
          >
            {({ open: _open }) => (
              <>
                <PopoverButton
                  className={`flex items-center gap-x-1 font-semibold text-sm text-white outline-none transition-colors duration-200 hover:text-[#FD105E] ${
                    servicesOpen ? "text-[#FD105E]" : ""
                  }`}
                  onMouseEnter={handleServicesMouseEnter}
                >
                  <Link href="/services">{tNav("services")}</Link>
                  <svg
                    aria-hidden="true"
                    className={`h-5 w-5 flex-none transition-transform duration-200 ${
                      servicesOpen ? "rotate-180" : ""
                    }`}
                    fill="currentColor"
                    viewBox="0 0 20 20"
                  >
                    <path
                      clipRule="evenodd"
                      d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z"
                      fillRule="evenodd"
                    />
                  </svg>
                </PopoverButton>

                {servicesOpen && (
                  <PopoverPanel
                    className="fade-in slide-in-from-top-2 absolute top-full left-1/2 z-10 mt-3 w-screen max-w-4xl -translate-x-1/2 animate-in overflow-hidden rounded-2xl bg-gradient-to-br from-[#1A2428] to-[#000] shadow-xl ring-1 ring-white/10 transition-all duration-200 ease-out"
                    onMouseEnter={handleServicesMouseEnter}
                    onMouseLeave={handleServicesMouseLeave}
                    static
                  >
                    <div className="p-8">
                      <div className="grid grid-cols-4 gap-8">
                        {servicesNav.map((section) => (
                          <div key={section.title}>
                            <h3 className="mb-4 font-semibold text-[#FD105E] text-sm uppercase tracking-wider">
                              {section.translationKey
                                ? tNav(section.translationKey)
                                : section.title}
                            </h3>
                            <div className="space-y-3">
                              {section.items.map((item) => {
                                const Icon = item.icon;
                                return (
                                  <Link
                                    className="group flex gap-x-3 rounded-lg p-3 transition-colors duration-200 hover:bg-white/5"
                                    href={item.href}
                                    key={item.name}
                                  >
                                    {Icon && (
                                      <Icon
                                        aria-hidden="true"
                                        className="h-6 w-6 flex-none text-neutral-400 transition-colors duration-200 group-hover:text-[#FD105E]"
                                      />
                                    )}
                                    <div>
                                      <p className="font-semibold text-sm text-white transition-colors duration-200 group-hover:text-[#FD105E]">
                                        {item.translationKey
                                          ? tNav(item.translationKey)
                                          : item.name}
                                      </p>
                                      {item.description && (
                                        <p className="mt-1 text-neutral-400 text-xs">
                                          {item.descriptionKey
                                            ? tNav(item.descriptionKey)
                                            : item.description}
                                        </p>
                                      )}
                                    </div>
                                  </Link>
                                );
                              })}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </PopoverPanel>
                )}
              </>
            )}
          </Popover>

          {/* Blog - Simple Dropdown */}
          <Popover
            className="relative"
            onMouseEnter={handleBlogMouseEnter}
            onMouseLeave={handleBlogMouseLeave}
          >
            {({ open: _open }) => (
              <>
                <PopoverButton
                  className={`flex items-center gap-x-1 font-semibold text-sm text-white outline-none transition-colors duration-200 hover:text-[#FD105E] ${
                    blogOpen ? "text-[#FD105E]" : ""
                  }`}
                  onMouseEnter={handleBlogMouseEnter}
                >
                  {tNav("blog")}
                  <svg
                    aria-hidden="true"
                    className={`h-5 w-5 flex-none transition-transform duration-200 ${
                      blogOpen ? "rotate-180" : ""
                    }`}
                    fill="currentColor"
                    viewBox="0 0 20 20"
                  >
                    <path
                      clipRule="evenodd"
                      d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z"
                      fillRule="evenodd"
                    />
                  </svg>
                </PopoverButton>

                {blogOpen && (
                  <PopoverPanel
                    className="fade-in slide-in-from-top-2 absolute top-full left-1/2 z-10 mt-3 w-screen max-w-sm -translate-x-1/2 animate-in overflow-hidden rounded-2xl bg-gradient-to-br from-[#1A2428] to-[#000] shadow-xl ring-1 ring-white/10 transition-all duration-200 ease-out"
                    onMouseEnter={handleBlogMouseEnter}
                    onMouseLeave={handleBlogMouseLeave}
                    static
                  >
                    <div className="p-4">
                      {blogLinks.map((item, index) => {
                        const Icon = item.icon;
                        return (
                          <Link
                            className={`group flex items-center gap-x-3 rounded-lg p-3 transition-colors duration-200 hover:bg-white/5 ${index === 0 ? "mb-1 border-white/5 border-b pb-3" : ""}`}
                            href={item.href}
                            key={item.name}
                          >
                            {Icon && (
                              <Icon
                                aria-hidden="true"
                                className="h-5 w-5 flex-none text-neutral-400 transition-colors duration-200 group-hover:text-[#FD105E]"
                              />
                            )}
                            <span className="font-semibold text-sm text-white transition-colors duration-200 group-hover:text-[#FD105E]">
                              {item.translationKey
                                ? tNav(item.translationKey)
                                : item.name}
                            </span>
                          </Link>
                        );
                      })}
                    </div>
                  </PopoverPanel>
                )}
              </>
            )}
          </Popover>

          {/* Direct Links */}
          {mainNavLinks.map((link) => (
            <Link
              className="font-semibold text-sm text-white transition-colors duration-200 hover:text-[#FD105E]"
              href={link.href}
              key={link.name}
            >
              {link.translationKey ? tNav(link.translationKey) : link.name}
            </Link>
          ))}
        </PopoverGroup>

        {/* CTA Button */}
        <div className="hidden lg:flex lg:flex-1 lg:items-center lg:justify-end lg:gap-4">
          <LanguageSwitcher />
          <Link
            className="rounded-xl bg-[#E00D54] px-6 py-2.5 font-semibold text-sm text-white shadow-[#FD105E]/20 shadow-lg transition-all duration-300 hover:bg-[#E00D54]/90 hover:shadow-[#FD105E]/30 hover:shadow-xl"
            href={ctaLink.href}
          >
            {ctaLink.translationKey
              ? tNav(ctaLink.translationKey)
              : ctaLink.name}
          </Link>
        </div>
      </nav>

      {/* Mobile menu */}
      <Dialog
        className="lg:hidden"
        onClose={setMobileMenuOpen}
        open={mobileMenuOpen}
      >
        <div className="fixed inset-0 z-50" />
        <DialogPanel className="fixed inset-y-0 right-0 z-50 w-full overflow-y-auto bg-gradient-to-br from-[#000] to-[#1A2428] px-6 py-6 sm:max-w-sm sm:ring-1 sm:ring-white/10">
          <div className="flex items-center justify-between">
            <Link
              className="p-2"
              href="/"
              onClick={(e) => {
                handleLogoClick(e);
                setMobileMenuOpen(false);
              }}
            >
              <span className="bg-gradient-to-r from-white to-[#FD105E] bg-clip-text font-bold text-2xl text-transparent">
                Eleva
              </span>
            </Link>
            <button
              className="rounded-md p-3 text-white"
              onClick={() => setMobileMenuOpen(false)}
              type="button"
            >
              <span className="sr-only">{tCommon("closeMenu")}</span>
              <IconX aria-hidden="true" className="h-6 w-6" />
            </button>
          </div>
          <div className="mt-6 flow-root">
            <div className="-my-6 divide-y divide-white/10">
              <div className="space-y-1 py-6">
                {/* Services Mobile — Collapsible */}
                <div>
                  <button
                    className="flex w-full items-center justify-between rounded-lg px-3 py-2.5 font-semibold text-[#FD105E] text-sm uppercase tracking-wider"
                    onClick={() => setMobileServicesOpen((prev) => !prev)}
                    type="button"
                  >
                    {tNav("services")}
                    <IconChevronDown
                      className={`transition-transform duration-200 ${mobileServicesOpen ? "rotate-180" : ""}`}
                      size={16}
                    />
                  </button>
                  <div
                    className={`overflow-hidden transition-all duration-300 ${
                      mobileServicesOpen
                        ? "max-h-[600px] opacity-100"
                        : "max-h-0 opacity-0"
                    }`}
                  >
                    <div className="space-y-1 pb-2 pl-3">
                      {servicesNav.map((section, sectionIndex) => (
                        <div key={section.title}>
                          <p
                            className={`px-3 text-neutral-500 text-xs ${
                              sectionIndex > 0 ? "mt-3" : ""
                            }`}
                          >
                            {section.translationKey
                              ? tNav(section.translationKey)
                              : section.title}
                          </p>
                          {section.items.map((item) => (
                            <Link
                              className="block rounded-lg px-3 py-1.5 text-neutral-200 text-sm hover:bg-white/5"
                              href={item.href}
                              key={item.name}
                              onClick={() => setMobileMenuOpen(false)}
                            >
                              {item.translationKey
                                ? tNav(item.translationKey)
                                : item.name}
                            </Link>
                          ))}
                        </div>
                      ))}
                    </div>
                  </div>
                </div>

                {/* Blog Mobile — Collapsible */}
                <div>
                  <button
                    className="flex w-full items-center justify-between rounded-lg px-3 py-2.5 font-semibold text-[#FD105E] text-sm uppercase tracking-wider"
                    onClick={() => setMobileBlogOpen((prev) => !prev)}
                    type="button"
                  >
                    {tNav("blog")}
                    <IconChevronDown
                      className={`transition-transform duration-200 ${mobileBlogOpen ? "rotate-180" : ""}`}
                      size={16}
                    />
                  </button>
                  <div
                    className={`overflow-hidden transition-all duration-300 ${
                      mobileBlogOpen
                        ? "max-h-[400px] opacity-100"
                        : "max-h-0 opacity-0"
                    }`}
                  >
                    <div className="space-y-0.5 pb-2 pl-3">
                      {blogLinks.map((item) => (
                        <Link
                          className="block rounded-lg px-3 py-1.5 text-neutral-200 text-sm hover:bg-white/5"
                          href={item.href}
                          key={item.name}
                          onClick={() => setMobileMenuOpen(false)}
                        >
                          {item.translationKey
                            ? tNav(item.translationKey)
                            : item.name}
                        </Link>
                      ))}
                    </div>
                  </div>
                </div>

                {/* Other Links Mobile */}
                {mainNavLinks.map((link) => (
                  <Link
                    className="block rounded-lg px-3 py-2.5 font-semibold text-sm text-white hover:bg-white/5"
                    href={link.href}
                    key={link.name}
                    onClick={() => setMobileMenuOpen(false)}
                  >
                    {link.translationKey
                      ? tNav(link.translationKey)
                      : link.name}
                  </Link>
                ))}
              </div>
              <div className="space-y-4 py-6">
                <div className="flex justify-center">
                  <LanguageSwitcher />
                </div>
                <Link
                  className="block rounded-xl bg-[#E00D54] px-6 py-3 text-center font-semibold text-sm text-white shadow-[#FD105E]/20 shadow-lg"
                  href={ctaLink.href}
                  onClick={() => setMobileMenuOpen(false)}
                >
                  {ctaLink.translationKey
                    ? tNav(ctaLink.translationKey)
                    : ctaLink.name}
                </Link>
              </div>
            </div>
          </div>
        </DialogPanel>
      </Dialog>
    </header>
  );
}
