"use client";
import { useEffect, useState } from "react";
import Image from "next/image";
import { Menu, X, ChevronDown, ChevronRight } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  NavigationMenu,
  NavigationMenuContent,
  NavigationMenuItem,
  NavigationMenuLink,
  NavigationMenuList,
  NavigationMenuTrigger,
} from "@/components/ui/navigation-menu";
import TopNavbar from "./TopNavbar";
import { useSettings } from "@/context/SettingsContext";
import { useCategories } from "@/hooks/useData";

// Mobile Menu Accordion Item Component
function MobileAccordionItem({ category, isOpen, onToggle, closeMobileMenu }) {
  const hasChildren = category.children && category.children.length > 0;

  return (
    <li className="border-b border-brand-gold/20">
      <div
        className="flex justify-between items-center py-3.5 cursor-pointer group"
        onClick={onToggle}
      >
        <Link
          href={`/${category.category_url}`}
          className="font-light text-gray-800 tracking-wider text-sm group-hover:text-brand-gold transition-colors"
        >
          {category.name}
        </Link>
        {hasChildren && (
          <div className="text-brand-gold">
            {isOpen ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
          </div>
        )}
      </div>

      {isOpen && hasChildren && (
        <ul className="pl-6 pb-3 space-y-2 bg-gradient-to-r from-brand-gold/5 to-transparent">
          {category.children.map((subcategory) => (
            <li key={subcategory.id}>
              {subcategory.children && subcategory.children.length > 0 ? (
                <MobileNestedAccordion
                  subcategory={subcategory}
                  closeMobileMenu={closeMobileMenu}
                />
              ) : (
                <Link
                  href={`/${subcategory.category_url}`}
                  className="block py-2 text-gray-600 text-sm hover:text-brand-gold hover:translate-x-1 transition-all"
                  onClick={closeMobileMenu}
                >
                  {subcategory.name}
                </Link>
              )}
            </li>
          ))}
        </ul>
      )}
    </li>
  );
}

// Nested Accordion for Subcategories with Children
function MobileNestedAccordion({ subcategory, closeMobileMenu }) {
  const [isOpen, setIsOpen] = useState(false);
  const hasChildren = subcategory.children && subcategory.children.length > 0;

  return (
    <>
      <div
        className="flex justify-between items-center py-2 cursor-pointer group"
        onClick={() => setIsOpen(!isOpen)}
      >
        <Link
          href={`/${subcategory.category_url}`}
          className="text-gray-700 text-sm group-hover:text-brand-gold transition-colors"
        >
          {subcategory.name}
        </Link>
        {hasChildren && (
          <div className="text-brand-gold">
            {isOpen ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
          </div>
        )}
      </div>

      {isOpen && hasChildren && (
        <ul className="pl-4 py-2 space-y-2">
          {subcategory.children.map((child) => (
            <li key={child.id}>
              <Link
                href={`/${child.category_url}`}
                className="block py-1.5 text-gray-500 text-xs hover:text-brand-gold hover:translate-x-1 transition-all"
                onClick={closeMobileMenu}
              >
                {child.name}
              </Link>
            </li>
          ))}
        </ul>
      )}
    </>
  );
}

export default function Navbar() {
  const { settings } = useSettings();
  const [scrolled, setScrolled] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [openAccordions, setOpenAccordions] = useState({});
  const pathname = usePathname();

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

  useEffect(() => {
    setMobileMenuOpen(false);
  }, [pathname]);

  const isHomePage = pathname === "/";

  const { data, isLoading, error } = useCategories();

  const allCategories = Array.isArray(data) ? data : data?.rows || [];

  const activeCategories = allCategories
    .filter((cat) => cat.category_status === 1 && cat.parent_id === null)
    .map((cat) => ({
      ...cat,
      children: Array.isArray(cat.children)
        ? cat.children.filter((child) => child.category_status === 1)
        : [],
    }));

  const toggleAccordion = (categoryName) => {
    setOpenAccordions((prev) => ({
      ...prev,
      [categoryName]: !prev[categoryName],
    }));
  };

  if (isLoading) {
    return (
      <header
        className={`sticky top-0 z-50 w-full bg-white/95 backdrop-blur-md border-b border-brand-gold/30`}
      >
        <TopNavbar />
        <div className="flex items-center justify-between max-w-[1600px] mx-auto px-6 py-6 max-md:hidden">
          <div className="animate-pulse bg-gradient-to-r from-brand-gold/30 to-brand-gold/10 h-16 w-32 rounded-sm"></div>
          <div className="animate-pulse bg-gradient-to-r from-brand-gold/30 to-brand-gold/10 h-8 w-64 rounded-sm max-lg:hidden"></div>
          <div className="animate-pulse h-8 w-32 bg-gradient-to-r from-brand-gold/30 to-brand-gold/10 rounded-sm"></div>
        </div>
      </header>
    );
  }

  if (error) {
    console.error("Failed to load categories:", error);
  }

  return (
    <>
      <style jsx global>{`
        @import url("https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@300;400;500;600;700&family=Montserrat:wght@200;300;400;500;600&display=swap");

        .navbar-luxury {
          font-family: "Montserrat", sans-serif;
        }

        .navbar-logo-text {
          font-family: "Cormorant Garamond", serif;
        }

        .nav-link-hover {
          position: relative;
        }

        .nav-link-hover::after {
          content: "";
          position: absolute;
          bottom: -4px;
          left: 50%;
          width: 0;
          height: 1px;
          background: linear-gradient(90deg, transparent, #ddbc5f, transparent);
          transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
          transform: translateX(-50%);
        }

        .nav-link-hover:hover::after {
          width: 100%;
        }

        .nav-link-active::after {
          content: "";
          position: absolute;
          bottom: -4px;
          left: 50%;
          width: 100%;
          height: 1px;
          background: linear-gradient(90deg, transparent, #ddbc5f, transparent);
          transform: translateX(-50%);
        }

        .menu-shimmer {
          position: relative;
          overflow: hidden;
        }

        .menu-shimmer::before {
          content: "";
          position: absolute;
          top: 0;
          left: -100%;
          width: 100%;
          height: 100%;
          background: linear-gradient(
            90deg,
            transparent,
            rgba(225, 191, 101, 0.1),
            transparent
          );
          animation: shimmer 3s infinite;
        }

        @keyframes shimmer {
          100% {
            left: 100%;
          }
        }

        .dropdown-enter {
          animation: dropdownSlide 0.3s ease-out;
        }

        @keyframes dropdownSlide {
          from {
            opacity: 0;
            transform: translateY(-10px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }

        .icon-bounce {
          transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .icon-bounce:hover {
          transform: translateY(-2px);
        }

        /* Fix NavigationMenuTrigger default styles */
        [data-radix-navigation-menu-trigger] {
          background-color: transparent !important;
        }

        [data-radix-navigation-menu-trigger]:hover {
          background-color: transparent !important;
        }

        [data-radix-navigation-menu-trigger][data-state="open"] {
          background-color: transparent !important;
        }

        /* Remove all background colors from navigation menu items */
        [data-slot="navigation-menu-link"],
        [data-slot="navigation-menu-link"]:hover,
        [data-slot="navigation-menu-link"]:focus,
        [data-slot="navigation-menu-link"]:active,
        [data-slot="navigation-menu-link"][data-active="true"] {
          background-color: transparent !important;
        }

        [data-slot="navigation-menu-trigger"],
        [data-slot="navigation-menu-trigger"]:hover,
        [data-slot="navigation-menu-trigger"]:focus,
        [data-slot="navigation-menu-trigger"]:active,
        [data-slot="navigation-menu-trigger"][data-state="open"] {
          background-color: transparent !important;
        }
      `}</style>

      <header
        className={`navbar-luxury ${
          isHomePage ? "fixed" : "sticky"
        } top-0 z-50 w-full transition-all duration-500`}
      >
        <div
          className={`absolute inset-0 z-0 transition-all duration-500 ${
            scrolled
              ? "bg-primary/90 backdrop-blur-sm"
              : isHomePage
                ? "bg-transparent"
                : "bg-primary"
          }`}
        />
        <div className="relative z-10">
          <TopNavbar />

          <nav className="relative max-w-[1600px] mx-auto px-6 py-4">
            <div className="flex items-center justify-between lg:flex lg:gap-4 xl:grid xl:grid-cols-3 xl:gap-8">
              {/* Logo - Left */}
              <Link href="/" className="relative group z-10 justify-self-start">
                <div className="relative w-[150px] h-[60px] lg:w-[180px] lg:h-[70px] xl:w-[220px] xl:h-[85px]">
                  <Image
                    src={
                      settings?.logo?.replace("/api", "") ||
                      "/images/logo-light.png"
                    }
                    alt="Jewelry Store Logo"
                    fill
                    sizes="(max-width: 768px) 180px, 220px"
                    className="object-contain transition-all duration-300 drop-shadow-xl"
                    priority
                  />
                </div>
              </Link>

              {/* Desktop Menu - Center */}
              <div className="hidden lg:flex justify-center col-start-2">
                <NavigationMenu>
                  <NavigationMenuList className="flex items-center gap-1">
                    {/* Home Link */}
                    <NavigationMenuItem>
                      <NavigationMenuLink asChild>
                        <Link
                          href="/"
                          className={`nav-link-hover ${pathname === "/" ? "nav-link-active" : ""} px-2 xl:px-4 py-2 text-[10px] xl:text-xs font-light tracking-wider xl:tracking-[0.2em] uppercase transition-all duration-300 ${
                            scrolled
                              ? "text-white hover:text-brand-gold"
                              : isHomePage
                                ? "text-white hover:text-brand-gold"
                                : "text-white hover:text-brand-gold"
                          }`}
                        >
                          Home
                        </Link>
                      </NavigationMenuLink>
                    </NavigationMenuItem>

                    {/* Dynamic Categories */}
                    {activeCategories.map((category) => {
                      const isActive =
                        pathname === `/${category.category_url}` ||
                        pathname.startsWith(`/${category.category_url}/`);
                      return (
                        <NavigationMenuItem key={category.id}>
                          <NavigationMenuTrigger
                            className={`nav-link-hover ${isActive ? "nav-link-active" : ""} px-2 xl:px-4 py-2 text-[10px] xl:text-xs font-light tracking-wider xl:tracking-[0.2em] uppercase bg-transparent border-none shadow-none transition-all duration-300 data-[state=open]:bg-transparent focus:bg-transparent hover:bg-transparent ${
                              scrolled
                                ? "text-white hover:text-brand-gold"
                                : isHomePage
                                  ? "text-white hover:text-brand-gold"
                                  : "text-white hover:text-brand-gold"
                            }`}
                          >
                            <Link
                              href={`/${category.category_url}`}
                              className="inline-block"
                            >
                              {category.name}
                            </Link>
                          </NavigationMenuTrigger>

                          {category.children &&
                            category.children.length > 0 && (
                              <NavigationMenuContent className="dropdown-enter">
                                <div className="w-[720px] bg-white/98 backdrop-blur-xl border border-brand-gold/30 shadow-2xl shadow-primary/10 rounded-none">
                                  <div className="grid grid-cols-3 gap-8 p-8">
                                    {/* Title + Links */}
                                    <div className="col-span-2 space-y-6">
                                      <div className="border-b border-brand-gold/30 pb-4">
                                        <h3 className="navbar-logo-text text-3xl font-medium text-primary tracking-wide">
                                          {category.name}
                                        </h3>
                                        <p className="text-xs text-brand-gold mt-1 tracking-widest uppercase font-medium">
                                          Collection
                                        </p>
                                      </div>

                                      <div className="grid grid-cols-2 gap-x-8 gap-y-3">
                                        {category.children.map(
                                          (subcategory) => (
                                            <Link
                                              key={subcategory.id}
                                              href={`/${subcategory.category_url}`}
                                              className="group flex items-center gap-2 text-sm text-gray-600 hover:text-primary transition-all duration-300 py-2"
                                              onClick={() =>
                                                setMobileMenuOpen(false)
                                              }
                                            >
                                              <span className="w-1 h-1 bg-primary rounded-full opacity-0 group-hover:opacity-100 transition-opacity"></span>
                                              <span className="font-medium tracking-wide group-hover:translate-x-1 transition-transform">
                                                {subcategory.name}
                                              </span>
                                            </Link>
                                          ),
                                        )}
                                      </div>
                                    </div>

                                    {/* Image */}
                                    <div className="col-span-1 flex items-center justify-center">
                                      {category?.category_image ? (
                                        <div className="relative w-full h-[240px] group overflow-hidden">
                                          <div className="absolute inset-0 bg-gradient-to-t from-primary/20 to-transparent z-10"></div>
                                          <Image
                                            src={category.category_image?.replace(
                                              "/api",
                                              "",
                                            )}
                                            alt={category.name}
                                            fill
                                            className="object-cover transition-transform duration-700 group-hover:scale-110"
                                          />
                                        </div>
                                      ) : (
                                        <div className="w-full h-[240px] bg-gradient-to-br from-brand-gold/20 to-brand-gold/5 flex items-center justify-center border border-brand-gold/30">
                                          <span className="navbar-logo-text text-2xl text-brand-gold/40 italic">
                                            {category.name}
                                          </span>
                                        </div>
                                      )}
                                    </div>
                                  </div>
                                </div>
                              </NavigationMenuContent>
                            )}
                        </NavigationMenuItem>
                      );
                    })}

                    {/* Static Links */}
                    {["Offers", "Schemes", "About", "Contact"].map((item) => {
                      const itemPath = `/${item.toLowerCase()}`;
                      const isActive =
                        pathname === itemPath ||
                        pathname.startsWith(`${itemPath}/`);
                      return (
                        <NavigationMenuItem key={item}>
                          <NavigationMenuLink asChild>
                            <Link
                              href={itemPath}
                              className={`nav-link-hover ${isActive ? "nav-link-active" : ""} px-2 xl:px-4 py-2 text-[10px] xl:text-xs font-light tracking-wider xl:tracking-[0.2em] uppercase transition-all duration-300 ${
                                scrolled
                                  ? "text-white hover:text-brand-gold"
                                  : isHomePage
                                    ? "text-white hover:text-brand-gold"
                                    : "text-white hover:text-brand-gold"
                              }`}
                            >
                              {item}
                            </Link>
                          </NavigationMenuLink>
                        </NavigationMenuItem>
                      );
                    })}
                  </NavigationMenuList>
                </NavigationMenu>
              </div>

              {/* Mobile menu button - Right (on mobile), Empty space (on desktop) */}
              <div className="flex justify-end lg:justify-self-end">
                <button
                  className={`lg:hidden p-2 transition-colors z-10 ${
                    scrolled
                      ? "text-white hover:text-brand-gold"
                      : isHomePage
                        ? "text-white hover:text-brand-gold"
                        : "text-white hover:text-brand-gold"
                  }`}
                  onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
                  aria-label="Toggle menu"
                >
                  {mobileMenuOpen ? (
                    <X className="h-6 w-6" />
                  ) : (
                    <Menu className="h-6 w-6" />
                  )}
                </button>
              </div>
            </div>

            {/* Mobile Menu - Slide from Right */}
            <div
              className={`fixed inset-y-0 right-0 z-50 w-full sm:w-80 bg-[#f5f1ea] shadow-2xl shadow-primary/20 transform ${
                mobileMenuOpen ? "translate-x-0" : "translate-x-full"
              } transition-transform duration-500 ease-out lg:hidden overflow-hidden`}
            >
              <div className="flex flex-col h-full">
                {/* Mobile Header */}
                <div className="flex justify-between items-center p-5 border-b border-brand-gold/20 bg-gradient-to-r from-brand-gold/10 to-transparent">
                  <span className="navbar-logo-text text-2xl font-light text-primary tracking-wider">
                    Menu
                  </span>
                  <button
                    onClick={() => setMobileMenuOpen(false)}
                    className="text-primary hover:text-brand-gold p-2 transition-colors"
                    aria-label="Close menu"
                  >
                    <X className="h-5 w-5" />
                  </button>
                </div>

                {/* Mobile Navigation */}
                <div className="overflow-y-auto flex-1 px-5 py-3">
                  <ul className="space-y-0.5">
                    <li className="border-b border-brand-gold/20 py-3.5">
                      <Link
                        href="/"
                        className="block text-gray-800 tracking-wider text-sm font-light hover:text-brand-gold transition-colors"
                        onClick={() => setMobileMenuOpen(false)}
                      >
                        Home
                      </Link>
                    </li>

                    {activeCategories.map((category) => (
                      <MobileAccordionItem
                        key={category.id}
                        category={category}
                        isOpen={!!openAccordions[category.name]}
                        onToggle={() => toggleAccordion(category.name)}
                        closeMobileMenu={() => setMobileMenuOpen(false)}
                      />
                    ))}

                    {["Schemes", "Offers", "Contact", "About"].map((item) => (
                      <li
                        key={item}
                        className="border-b border-brand-gold/20 py-3.5"
                      >
                        <Link
                          href={`/${item.toLowerCase()}`}
                          className="block text-gray-800 tracking-wider text-sm font-light hover:text-brand-gold transition-colors"
                          onClick={() => setMobileMenuOpen(false)}
                        >
                          {item}
                        </Link>
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            </div>

            {/* Mobile Menu Overlay */}
            {mobileMenuOpen && (
              <div
                className="fixed inset-0 bg-primary/60 backdrop-blur-sm z-40 lg:hidden"
                onClick={() => setMobileMenuOpen(false)}
              />
            )}
          </nav>
        </div>
      </header>
    </>
  );
}
