import { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "motion/react";
import { Plus, ArrowRight } from "lucide-react";
import { cls } from "@/lib/utils";
import Button from "@/components/ui/Button";

interface NavbarCenteredProps {
  logo: string;
  navItems: { name: string; href: string }[];
  ctaButton: { text: string; href: string };
}

const handleNavClick = (e: React.MouseEvent<HTMLAnchorElement>, href: string, onClose?: () => void) => {
  if (href.startsWith("#")) {
    e.preventDefault();
    const element = document.getElementById(href.slice(1));
    element?.scrollIntoView({ behavior: "smooth", block: "start" });
  }
  onClose?.();
};

const NavbarCentered = ({ logo, navItems, ctaButton }: NavbarCenteredProps) => {
  const [isScrolled, setIsScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleScroll = () => setIsScrolled(window.scrollY > 50);
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape" && menuOpen) setMenuOpen(false);
    };
    const handleClickOutside = (e: MouseEvent) => {
      if (menuOpen && menuRef.current && !menuRef.current.contains(e.target as Node)) {
        setMenuOpen(false);
      }
    };
    document.addEventListener("keydown", handleKeyDown);
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("keydown", handleKeyDown);
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [menuOpen]);

  return (
    <>
      <nav
        data-section="navbar"
        className={cls(
          "fixed z-1000 top-0 left-0 w-full transition-all duration-500 ease-in-out",
          isScrolled ? "h-15 bg-background/80 backdrop-blur-sm" : "h-20 bg-background/0 backdrop-blur-0"
        )}
      >
        <div className="relative mx-auto flex items-center justify-between h-full w-content-width">
          <a href="/" className="text-xl font-medium text-foreground">{logo}</a>

          <div className="hidden md:flex absolute left-1/2 -translate-x-1/2 items-center gap-6">
            {navItems.map((item) => (
              <a
                key={item.name}
                href={item.href}
                onClick={(e) => handleNavClick(e, item.href)}
                className="text-base text-foreground hover:opacity-70 transition-opacity"
              >
                {item.name}
              </a>
            ))}
          </div>

          <div className="flex items-center gap-2 xl:gap-3 2xl:gap-4">
            <Button text={ctaButton.text} href={ctaButton.href} variant="primary" animate={false} />

            <div
              className="flex md:hidden items-center justify-center shrink-0 size-9 rounded cursor-pointer primary-button"
              onClick={() => setMenuOpen(!menuOpen)}
            >
              <Plus
                className={cls("w-1/2 h-1/2 text-primary-cta-text transition-transform duration-300", menuOpen ? "rotate-45" : "rotate-0")}
                strokeWidth={1.5}
              />
            </div>
          </div>
        </div>
      </nav>

      <AnimatePresence>
        {menuOpen && (
          <motion.div
            ref={menuRef}
            initial={{ y: "-135%" }}
            animate={{ y: 0 }}
            exit={{ y: "-135%" }}
            transition={{ type: "spring", damping: 26, stiffness: 170 }}
            className="md:hidden fixed z-1000 top-3 left-3 right-3 p-6 rounded card"
          >
            <div className="flex items-center justify-between mb-6">
              <p className="text-xl text-foreground">Menu</p>
              <div
                className="flex items-center justify-center shrink-0 size-9 rounded cursor-pointer primary-button"
                onClick={() => setMenuOpen(false)}
              >
                <Plus className="w-1/2 h-1/2 text-primary-cta-text rotate-45" strokeWidth={1.5} />
              </div>
            </div>

            <div className="flex flex-col gap-4">
              {navItems.map((item, index) => (
                <div key={item.name}>
                  <a
                    href={item.href}
                    onClick={(e) => handleNavClick(e, item.href, () => setMenuOpen(false))}
                    className="flex items-center justify-between py-2 text-base font-medium text-foreground"
                  >
                    {item.name}
                    <ArrowRight className="size-4 text-foreground" strokeWidth={1.5} />
                  </a>
                  {index < navItems.length - 1 && (
                    <div className="h-px bg-linear-to-r from-transparent via-foreground/20 to-transparent" />
                  )}
                </div>
              ))}
            </div>

            <div className="mt-6">
              <Button text={ctaButton.text} href={ctaButton.href} variant="primary" animate={false} className="w-full" />
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
};

const CustomNavbar = ({ logo, navItems, ctaButton }: NavbarCenteredProps) => {
  const [isScrolled, setIsScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 80);
    };
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  const handleNavClick = (e: React.MouseEvent<HTMLAnchorElement>, href: string, onClose?: () => void) => {
    if (href.startsWith("#")) {
      e.preventDefault();
      const element = document.getElementById(href.slice(1));
      element?.scrollIntoView({ behavior: "smooth", block: "start" });
    }
    onClose?.();
  };

  return (
    <>
      <motion.nav
        initial={{ y: -100 }}
        animate={{ y: 0 }}
        transition={{ duration: 0.6, ease: [0.25, 0.46, 0.45, 0.94] }}
        className={cls(
          "fixed top-0 left-0 right-0 z-[1000] w-full transition-all duration-350 ease-[cubic-bezier(0.25,0.46,0.45,0.94)]",
          isScrolled
            ? "bg-[rgba(10,10,10,0.92)] backdrop-blur-[14px] border-b border-[rgba(125,28,46,0.25)] h-[60px] md:h-[72px]"
            : "bg-transparent border-b-transparent h-[60px] md:h-[72px]"
        )}
      >
        <div className="w-content-width mx-auto h-full flex items-center justify-between px-4 md:px-0">
          {/* LEFT - Logo */}
          <motion.div
            initial={{ x: -20, opacity: 0 }}
            animate={{ x: 0, opacity: 1 }}
            transition={{ duration: 0.6, ease: "easeOut", delay: 0.2 }}
            className="flex items-center gap-3 cursor-pointer"
            onClick={(e: any) => handleNavClick(e, "#hero")}
          >
            <div className="w-[38px] h-[38px] bg-[#7D1C2E] rounded-[5px] flex items-center justify-center">
              <span className="font-tight font-black text-white text-[24px] leading-none">X</span>
            </div>
            <div className="flex flex-col justify-center">
              <div className="font-tight font-black text-[22px] leading-none text-white tracking-wide">
                APE<span className="text-[#7D1C2E]">X</span>
              </div>
              <div className="font-tight font-bold text-[10px] leading-none text-[rgba(255,255,255,0.28)] tracking-[5px] mt-1 uppercase">
                Web Group
              </div>
            </div>
          </motion.div>

          {/* CENTER - Links */}
          <div className="hidden md:flex items-center gap-[48px]">
            {navItems.filter(item => ["Services", "Packages", "Guarantee", "Contact"].includes(item.name)).map((item) => (
              <a
                key={item.name}
                href={item.href}
                onClick={(e) => handleNavClick(e, item.href)}
                className="group relative font-sans font-bold text-[13px] tracking-[2px] uppercase text-[rgba(255,255,255,0.65)] hover:text-[#F5F5F5] transition-colors duration-250"
              >
                {item.name}
                <span className="absolute -bottom-1 left-0 w-full h-[1px] bg-[#7D1C2E] origin-left scale-x-0 group-hover:scale-x-100 transition-transform duration-250 ease-out" />
              </a>
            ))}
          </div>

          {/* RIGHT - CTA */}
          <motion.div
            initial={{ x: 20, opacity: 0 }}
            animate={{ x: 0, opacity: 1 }}
            transition={{ duration: 0.6, ease: "easeOut", delay: 0.4 }}
            className="hidden md:block"
          >
            <a
              href={ctaButton.href}
              onClick={(e) => handleNavClick(e, ctaButton.href)}
              className="inline-flex items-center justify-center rounded-full bg-[rgba(255,255,255,0.07)] border border-[rgba(255,255,255,0.18)] backdrop-blur-[10px] px-[24px] py-[10px] font-sans font-bold text-[12px] tracking-[2px] uppercase text-white hover:bg-[rgba(125,28,46,0.35)] hover:border-[rgba(125,28,46,0.6)] hover:scale-[1.03] transition-all duration-250 ease-out"
            >
              {ctaButton.text} <span className="ml-2">→</span>
            </a>
          </motion.div>

          {/* Mobile Toggle */}
          <button
            className="md:hidden text-white p-2"
            onClick={() => setMenuOpen(!menuOpen)}
          >
            {menuOpen ? (
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
            ) : (
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
            )}
          </button>
        </div>
      </motion.nav>

      {/* Mobile Menu Overlay */}
      <AnimatePresence>
        {menuOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-[999] bg-[rgba(10,10,10,0.98)] backdrop-blur-xl flex flex-col items-center justify-center"
          >
            <div className="flex flex-col items-center gap-8">
              {navItems.filter(item => ["Services", "Packages", "Guarantee", "Contact"].includes(item.name)).map((item, i) => (
                <motion.a
                  key={item.name}
                  href={item.href}
                  initial={{ y: 20, opacity: 0 }}
                  animate={{ y: 0, opacity: 1 }}
                  exit={{ y: 20, opacity: 0 }}
                  transition={{ delay: i * 0.1 }}
                  onClick={(e: any) => handleNavClick(e, item.href, () => setMenuOpen(false))}
                  className="font-sans font-bold text-[24px] tracking-[2px] uppercase text-white"
                >
                  {item.name}
                </motion.a>
              ))}
              <motion.a
                href={ctaButton.href}
                initial={{ y: 20, opacity: 0 }}
                animate={{ y: 0, opacity: 1 }}
                exit={{ y: 20, opacity: 0 }}
                transition={{ delay: 0.4 }}
                onClick={(e: any) => handleNavClick(e, ctaButton.href, () => setMenuOpen(false))}
                className="mt-8 inline-flex items-center justify-center rounded-full bg-[rgba(125,28,46,0.35)] border border-[rgba(125,28,46,0.6)] px-[32px] py-[14px] font-sans font-bold text-[14px] tracking-[2px] uppercase text-white"
              >
                {ctaButton.text} <span className="ml-2">→</span>
              </motion.a>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
};

export default CustomNavbar;
