"use client";

import { useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { ChevronDown, Menu, X, ChevronRight } from "lucide-react";
import { BASE_URL } from "@/Constant";

interface MenuItem {
  title: string;
  path: string;
  submenu?: MenuItem[];
}

const Navbar = ({ data }: any) => {
  const [mobileMenuOpen, setMobileMenuOpen] = useState<boolean>(false);
  const [activeDropdown, setActiveDropdown] = useState<string | null>(null);
  const [mobileActiveSubmenu, setMobileActiveSubmenu] = useState<string | null>(
    null
  );
  let hideDropdownTimeout: NodeJS.Timeout | null = null;

  const menuItems: MenuItem[] = [
    {
      title: "Home",
      path: "/",
    },
    {
      title: "About IAAB",
      path: "#",
      submenu: [
        { title: "About IAAB", path: "/about" },
        { title: "Structure", path: "/structure" },
        { title: "Roles / Code of Conducts", path: "/roles" },
      ],
    },
    {
      title: "Member",
      path: "#",
      submenu: [
        { title: "Members", path: "/members" },
        { title: "Members Login", path: "/memberlogins" },
      ],
    },
    {
      title: "Recognized",
      path: "#",
      submenu: [
        { title: "Accreditation Body", path: "/accreditationbody" },
        { title: "Certification Body", path: "/certificationbody" },
        {
          title: "Personnel Certification Body",
          path: "/personnelcertificationbody",
        },
      ],
    },
    {
      title: "IAAB Publications",
      path: "#",
      submenu: [
        { title: "Guideline Document", path: "/guideline" },
        { title: "GLA", path: "/gla" },
      ],
    },
    {
      title: "Contact Us",
      path: "#",
      submenu: [
        { title: "Contact", path: "/contact" },
        { title: "FAQ", path: "/faq" },
      ],
    },
  ];

  const handleMouseEnter = (title: string) => {
    if (hideDropdownTimeout) {
      clearTimeout(hideDropdownTimeout);
    }
    setActiveDropdown(title);
  };

  const handleMouseLeave = () => {
    hideDropdownTimeout = setTimeout(() => {
      setActiveDropdown(null);
    }, 200);
  };

  const toggleMobileMenu = () => {
    setMobileMenuOpen(!mobileMenuOpen);
    if (mobileMenuOpen) {
      setMobileActiveSubmenu(null);
    }
  };

  const toggleMobileSubmenu = (title: string) => {
    setMobileActiveSubmenu(mobileActiveSubmenu === title ? null : title);
  };

  const closeMobileMenu = () => {
    setMobileMenuOpen(false);
    setMobileActiveSubmenu(null);
  };

  return (
    <>
      <nav className="relative z-50">
        <div className="bg-transparent mx-auto">
          <div className="flex w-full justify-between py-2.5 px-4 rounded-lg border border-gray-300 bg-white/80 backdrop-blur-sm">
            <div className="flex items-center">
              <Link href="/" onClick={closeMobileMenu}>
                <Image
                  src={`${BASE_URL}${data?.headerLogo}`}
                  alt="IAAB Logo"
                  width={100}
                  height={100}
                  className="w-auto h-16 transition-transform hover:scale-105"
                  unoptimized={true}
                />
              </Link>
            </div>

            {/* Desktop Navigation */}
            <div className="hidden md:flex items-center">
              <div className="flex space-x-3">
                {menuItems.map((item) => (
                  <div
                    key={item.title}
                    className="relative"
                    onMouseEnter={() => handleMouseEnter(item.title)}
                    onMouseLeave={handleMouseLeave}
                  >
                    <Link
                      href={item.path}
                      className="text-gray-900 hover:bg-[#f2f3f6] hover:rounded-[11px] hover:text-black hover:text-[14.2px] px-3 py-2 text-sm font-medium flex items-center transition-all duration-200"
                    >
                      {item.title}
                      {item.submenu && <ChevronDown className="ml-1 h-4 w-4" />}
                    </Link>
                    {item.submenu && activeDropdown === item.title && (
                      <div
                        className="absolute left-0 mt-2 w-48 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-50 transform transition-all duration-200 ease-out"
                        onMouseEnter={() => handleMouseEnter(item.title)}
                        onMouseLeave={handleMouseLeave}
                      >
                        <div className="py-1">
                          {item.submenu.map((subItem) => (
                            <Link
                              onClick={() => {
                                if (subItem?.title === "Members Login")
                                  localStorage.setItem("loginType", "member");
                              }}
                              key={subItem.title}
                              href={subItem.path}
                              className="block px-4 py-2 text-sm text-gray-700 hover:bg-btn hover:text-gray-900 transition-colors duration-150"
                            >
                              {subItem.title}
                            </Link>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                ))}

                <Link
                  href="/login&signup"
                  className="inline-flex hover:bg-btnhover hover:scale-105 w-36 items-center justify-center px-6 py-2 border border-transparent text-sm font-medium rounded-full text-black bg-btn transition-all duration-200"
                >
                  Login
                </Link>
              </div>
            </div>

            {/* Mobile menu button */}
            <div className="flex items-center md:hidden">
              <button
                onClick={toggleMobileMenu}
                className="inline-flex items-center justify-center p-2 rounded-md text-gray-700 hover:text-gray-900 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-blue-500 transition-colors duration-200"
                aria-label="Toggle mobile menu"
              >
                {mobileMenuOpen ? (
                  <X className="h-6 w-6 transform transition-transform duration-200" />
                ) : (
                  <Menu className="h-6 w-6 transform transition-transform duration-200" />
                )}
              </button>
            </div>
          </div>
        </div>
      </nav>

      {/* Mobile menu overlay */}
      <div
        className={`fixed inset-0 bg-black/50 backdrop-blur-sm z-40 md:hidden transition-opacity duration-300 ${
          mobileMenuOpen ? "opacity-100" : "opacity-0 pointer-events-none"
        }`}
        onClick={closeMobileMenu}
      />

      {/* Mobile menu panel */}
      <div
        className={`fixed top-0 right-0 h-full w-80 bg-white shadow-2xl z-50 md:hidden transform transition-transform duration-300 ease-in-out ${
          mobileMenuOpen ? "translate-x-0" : "translate-x-full"
        }`}
      >
        <div className="flex flex-col h-full">
          {/* Mobile menu header */}
          <div className="flex items-center justify-between p-4 border-b border-gray-200">
            <Link href="/" onClick={closeMobileMenu}>
              <Image
                src={`${BASE_URL}${data?.headerLogo}`}
                alt="IAAB Logo"
                width={80}
                height={80}
                className="w-auto h-12"
                unoptimized={true}
              />
            </Link>
            <button
              onClick={closeMobileMenu}
              className="p-2 rounded-md text-gray-700 hover:text-gray-900 hover:bg-gray-100 transition-colors duration-200"
              aria-label="Close menu"
            >
              <X className="h-6 w-6" />
            </button>
          </div>

          {/* Mobile menu content */}
          <div className="flex-1 overflow-y-auto px-4 py-6">
            <div className="space-y-2">
              {menuItems.map((item) => (
                <div
                  key={item.title}
                  className="border-b border-gray-100 last:border-b-0"
                >
                  {item.submenu ? (
                    <div>
                      <button
                        onClick={() => toggleMobileSubmenu(item.title)}
                        className="w-full flex items-center justify-between p-3 text-left text-gray-900 hover:bg-gray-50 rounded-lg transition-colors duration-200 font-medium"
                      >
                        <span>{item.title}</span>
                        <ChevronRight
                          className={`h-5 w-5 text-gray-400 transition-transform duration-200 ${
                            mobileActiveSubmenu === item.title
                              ? "rotate-90"
                              : ""
                          }`}
                        />
                      </button>
                      <div
                        className={`overflow-hidden transition-all duration-300 ease-in-out ${
                          mobileActiveSubmenu === item.title
                            ? "max-h-96 opacity-100"
                            : "max-h-0 opacity-0"
                        }`}
                      >
                        <div className="pl-4 pb-2 space-y-1">
                          {item.submenu.map((subItem) => (
                            <Link
                              key={subItem.title}
                              href={subItem.path}
                              onClick={() => {
                                if (subItem?.title === "Members Login")
                                  localStorage.setItem("loginType", "member");
                                closeMobileMenu();
                              }}
                              className="block p-3 text-sm text-gray-700 hover:text-gray-900 hover:bg-gray-50 rounded-lg transition-colors duration-200"
                            >
                              {subItem.title}
                            </Link>
                          ))}
                        </div>
                      </div>
                    </div>
                  ) : (
                    <Link
                      href={item.path}
                      onClick={closeMobileMenu}
                      className="block p-3 text-gray-900 hover:bg-gray-50 rounded-lg transition-colors duration-200 font-medium"
                    >
                      {item.title}
                    </Link>
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* Mobile menu footer */}
          <div className="p-4 border-t border-gray-200">
            <Link
              href="/login&signup"
              className="block w-full text-center px-4 py-2 mt-4 text-sm font-medium rounded-full text-black bg-gradient-to-r from-yellow-200 via-pink-200 to-blue-200 hover:from-yellow-300 hover:via-pink-300 hover:to-blue-300"
            >
              Login
            </Link>
          </div>
        </div>
      </div>
    </>
  );
};

export default Navbar;
