"use client";
import { cn } from "@/lib/utils";
import { IconMenu2, IconX, IconChevronDown } from "@tabler/icons-react";
import {
  motion,
  AnimatePresence,
  useScroll,
  useMotionValueEvent,
} from "motion/react";
import Link from "next/link";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { Logo } from "./logo";
import { CalButton } from "./cal-button";
import {
  navigation,
  directLinks,
  type NavigationItem,
} from "@/data/links/navigation";

interface NavbarProps {
  navItems: NavigationItem[];
  visible: boolean;
}

export const Navbar = () => {
  // Combine navigation items with dropdown menus and direct links
  const navItems = [...navigation, ...directLinks];

  const ref = useRef<HTMLDivElement>(null);
  const { scrollY } = useScroll();
  const [visible, setVisible] = useState<boolean>(false);

  useMotionValueEvent(scrollY, "change", (latest) => {
    if (latest > 100) {
      setVisible(true);
    } else {
      setVisible(false);
    }
  });

  return (
    <motion.div
      ref={ref}
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.3 }}
      className="w-full fixed top-2 inset-x-0 z-50"
    >
      <DesktopNav visible={visible} navItems={navItems} />
      <MobileNav visible={visible} navItems={navItems} />
    </motion.div>
  );
};

const DesktopNav = ({ navItems, visible }: NavbarProps) => {
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
  const [dropdownOpen, setDropdownOpen] = useState<number | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const triggersRef = useRef(new Map<number, HTMLButtonElement | null>());

  const closeDropdown = useCallback(() => setDropdownOpen(null), []);

  // Sur tactile, aucun `pointerleave` ne survient jamais : sans ces deux
  // sorties, un menu ouvert au doigt resterait ouvert indefiniment.
  useEffect(() => {
    if (dropdownOpen === null) return;

    const handlePointerDown = (event: PointerEvent) => {
      if (!containerRef.current?.contains(event.target as Node)) {
        closeDropdown();
      }
    };
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key !== "Escape") return;
      triggersRef.current.get(dropdownOpen)?.focus();
      closeDropdown();
    };

    document.addEventListener("pointerdown", handlePointerDown);
    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("pointerdown", handlePointerDown);
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [dropdownOpen, closeDropdown]);

  return (
    <motion.div
      ref={containerRef}
      onPointerLeave={(event) => {
        // Un pointeur tactile emet `pointerleave` des la fin du tap : sans ce
        // filtre, le menu se refermerait dans la foulee de son ouverture.
        if (event.pointerType !== "mouse") return;
        setHoveredIndex(null);
        setDropdownOpen(null);
      }}
      animate={{
        width: visible ? "50%" : "80%",
        backgroundColor: visible
          ? "rgba(255,255,255,0.95)"
          : "rgba(255,255,255,0.5)",
        backdropFilter: visible ? "blur(10px)" : "blur(5px)",
        y: visible ? 4 : 0,
        boxShadow: visible
          ? "0 10px 30px -10px rgba(0,0,0,0.1)"
          : "0 0 0 transparent",
      }}
      initial={{
        width: "80%",
        scale: 0.95,
        opacity: 0,
      }}
      whileInView={{
        scale: 1,
        opacity: 1,
      }}
      transition={{
        duration: 0.3,
        ease: "easeInOut",
      }}
      className={cn(
        "hidden lg:flex flex-row self-center items-center justify-between py-3 mx-auto px-8 rounded-full relative z-[100]"
      )}
    >
      <Logo />
      <motion.div
        className="lg:flex flex-row flex-1 items-center justify-center space-x-2 text-sm"
        animate={{
          scale: 1,
          justifyContent: visible ? "flex-end" : "center",
        }}
      >
        {navItems.map((navItem, idx) => (
          <div
            key={`nav-item-${idx}`}
            onPointerEnter={(event) => {
              // Le survol reste reserve aux pointeurs fins : sur tactile, c'est
              // le `onClick` du declencheur qui pilote l'ouverture.
              if (event.pointerType !== "mouse") return;
              setHoveredIndex(idx);
              setDropdownOpen(navItem.children ? idx : null);
            }}
            onBlur={(event) => {
              if (event.currentTarget.contains(event.relatedTarget)) return;
              setDropdownOpen((current) => (current === idx ? null : current));
            }}
            className="relative group"
          >
            {navItem.children ? (
              // Dropdown menu item
              <div className="relative">
                <button
                  type="button"
                  ref={(node) => {
                    triggersRef.current.set(idx, node);
                  }}
                  aria-expanded={dropdownOpen === idx}
                  aria-controls={`nav-dropdown-${idx}`}
                  onClick={() =>
                    setDropdownOpen(dropdownOpen === idx ? null : idx)
                  }
                  onFocus={() => setHoveredIndex(idx)}
                  className="text-gray-900 font-semibold relative px-3 py-1.5 transition-colors flex items-center gap-1"
                >
                  <span className="relative z-10">{navItem.label}</span>
                  <IconChevronDown
                    className={cn(
                      "w-4 h-4 relative z-10 transition-transform duration-200",
                      dropdownOpen === idx && "rotate-180"
                    )}
                    aria-hidden="true"
                  />
                  {hoveredIndex === idx && (
                    <motion.div
                      layoutId="menu-hover"
                      className="absolute inset-0 rounded-full"
                      initial={{ opacity: 0 }}
                      animate={{
                        opacity: 1,
                        background:
                          "linear-gradient(145deg, rgba(255,255,255,0.8) 0%, rgba(255,255,255,0.2) 100%)",
                        boxShadow: "0 4px 15px rgba(0,0,0,0.05)",
                      }}
                      exit={{
                        opacity: 0,
                      }}
                      transition={{
                        duration: 0.05,
                      }}
                    />
                  )}
                </button>
                <AnimatePresence>
                  {dropdownOpen === idx && (
                    <motion.div
                      initial={{ opacity: 0, y: -10 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -10 }}
                      transition={{ duration: 0.2 }}
                      id={`nav-dropdown-${idx}`}
                      className="absolute left-1/2 -translate-x-1/2 top-full mt-2 w-64 bg-white backdrop-blur-xl rounded-2xl shadow-lg overflow-hidden"
                    >
                      {navItem.children.map((child, childIdx) => (
                        <Link
                          key={`child-${idx}-${childIdx}`}
                          href={child.href || "#"}
                          onClick={closeDropdown}
                          className="block px-4 py-3 hover:bg-gray-50 transition-colors border-b border-gray-100 last:border-b-0"
                        >
                          <div className="font-semibold text-gray-900">
                            {child.label}
                          </div>
                          {child.description && (
                            <div className="text-xs text-gray-700 mt-1">
                              {child.description}
                            </div>
                          )}
                        </Link>
                      ))}
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            ) : (
              // Direct link item
              <Link
                className="text-gray-900 font-semibold relative px-3 py-1.5 transition-colors block"
                href={navItem.href || "#"}
                onFocus={() => setHoveredIndex(idx)}
              >
                <span className="relative z-10">{navItem.label}</span>
                {hoveredIndex === idx && (
                  <motion.div
                    layoutId="menu-hover"
                    className="absolute inset-0 rounded-full"
                    initial={{ opacity: 0 }}
                    animate={{
                      opacity: 1,
                      background:
                        "linear-gradient(145deg, rgba(255,255,255,0.8) 0%, rgba(255,255,255,0.2) 100%)",
                      boxShadow: "0 4px 15px rgba(0,0,0,0.05)",
                    }}
                    exit={{
                      opacity: 0,
                    }}
                    transition={{
                      duration: 0.05,
                    }}
                  />
                )}
              </Link>
            )}
          </div>
        ))}
      </motion.div>

      <AnimatePresence mode="popLayout" initial={false}>
        {!visible && (
          <motion.div
            initial={{ opacity: 0, x: 20 }}
            animate={{
              opacity: 1,
              x: 0,
              transition: {
                duration: 0.2,
              },
            }}
            exit={{
              opacity: 0,
              x: 20,
              transition: {
                duration: 0.2,
              },
            }}
          >
            <CalButton className="px-5 py-2.5">
              Prendre rendez-vous
            </CalButton>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  );
};

const MobileNav = ({ navItems, visible }: NavbarProps) => {
  const [open, setOpen] = useState(false);
  const [expandedItem, setExpandedItem] = useState<number | null>(null);

  return (
    <>
      <motion.div
        animate={{
          backdropFilter: "blur(16px)",
          background: visible
            ? "rgba(255, 255, 255, 0.95)"
            : "rgba(255, 255, 255, 0.8)",
          width: visible ? "85%" : "90%",
          y: visible ? 4 : 0,
          borderRadius: open ? "24px" : "9999px",
          padding: "12px 20px",
          boxShadow: visible
            ? "0 10px 30px -10px rgba(0,0,0,0.1)"
            : "0 0 0 transparent",
        }}
        initial={{
          width: "85%",
          scale: 0.95,
          opacity: 0,
        }}
        whileInView={{
          scale: 1,
          opacity: 1,
        }}
        transition={{
          duration: 0.3,
          ease: "easeInOut",
        }}
        className={cn(
          "flex relative flex-col lg:hidden w-full justify-between items-center max-w-[calc(100vw-2rem)] mx-auto z-50"
        )}
      >
        <div className="flex flex-row justify-between items-center w-full">
          <Logo />
          <motion.button
            type="button"
            aria-label={open ? "Fermer le menu" : "Ouvrir le menu"}
            aria-expanded={open}
            whileHover={{ scale: 1.1 }}
            whileTap={{ scale: 0.9 }}
            onClick={() => setOpen(!open)}
            className="p-2 -m-2 focus:outline-none focus:ring-2 focus:ring-orange-500 rounded-lg"
          >
            {open ? (
              <IconX className="text-gray-900" aria-hidden="true" />
            ) : (
              <IconMenu2 className="text-gray-900" aria-hidden="true" />
            )}
          </motion.button>
        </div>

        <AnimatePresence>
          {open && (
            <motion.div
              initial={{
                opacity: 0,
                height: 0,
                y: -10,
              }}
              animate={{
                opacity: 1,
                height: "auto",
                y: 0,
              }}
              exit={{
                opacity: 0,
                height: 0,
                y: -10,
              }}
              transition={{
                duration: 0.2,
                ease: "easeInOut",
              }}
              className="flex rounded-2xl absolute top-16 backdrop-blur-xl bg-white/95 inset-x-0 z-50 flex-col items-start justify-start gap-2 w-full px-6 py-6 shadow-lg"
            >
              {/* Cal.com CTA Button at top of mobile menu */}
              <CalButton className="w-full md:w-auto md:self-center text-center px-5 py-3 mb-2">
                Prendre rendez-vous
              </CalButton>

              {navItems.map((navItem, idx) => (
                <motion.div
                  key={`link=${idx}`}
                  initial={{ opacity: 0, x: -10 }}
                  animate={{
                    opacity: 1,
                    x: 0,
                    transition: {
                      delay: idx * 0.05,
                    },
                  }}
                  className="w-full"
                >
                  {navItem.children ? (
                    // Accordion item with children
                    <div className="w-full">
                      <button
                        onClick={() =>
                          setExpandedItem(expandedItem === idx ? null : idx)
                        }
                        className="w-full flex items-center justify-between text-gray-900 hover:text-gray-700 transition-colors py-2"
                      >
                        <span className="font-semibold">{navItem.label}</span>
                        <motion.div
                          animate={{
                            rotate: expandedItem === idx ? 180 : 0,
                          }}
                          transition={{ duration: 0.2 }}
                        >
                          <IconChevronDown className="w-4 h-4" />
                        </motion.div>
                      </button>
                      <AnimatePresence>
                        {expandedItem === idx && (
                          <motion.div
                            initial={{ height: 0, opacity: 0 }}
                            animate={{ height: "auto", opacity: 1 }}
                            exit={{ height: 0, opacity: 0 }}
                            transition={{ duration: 0.2 }}
                            className="overflow-hidden pl-4"
                          >
                            {navItem.children.map((child, childIdx) => (
                              <Link
                                key={`child-${idx}-${childIdx}`}
                                href={child.href || "#"}
                                onClick={() => setOpen(false)}
                                className="block py-2 text-sm text-gray-800 hover:text-gray-900 transition-colors font-medium"
                              >
                                {child.label}
                              </Link>
                            ))}
                          </motion.div>
                        )}
                      </AnimatePresence>
                    </div>
                  ) : (
                    // Direct link item
                    <Link
                      href={navItem.href || "#"}
                      onClick={() => setOpen(false)}
                      className="block text-gray-900 hover:text-gray-700 transition-colors py-2 font-semibold"
                    >
                      {navItem.label}
                    </Link>
                  )}
                </motion.div>
              ))}
            </motion.div>
          )}
        </AnimatePresence>
      </motion.div>
    </>
  );
};
