"use client";
import React, { Fragment } from "react";
import { Popover, Transition } from "@headlessui/react";
import {
  ChevronDown,
  ChevronRight,
  Menu as MenuIcon,
  X,
  Zap,
} from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";

const products = {
  categories: [
    {
      name: "Circuit Protection",
      items: [
        {
          name: "Circuit Breakers",
          href: "#",
          description: "High-performance protection devices",
        },
        {
          name: "Fuses & Accessories",
          href: "#",
          description: "Complete range of fuse solutions",
        },
        {
          name: "Surge Protection",
          href: "#",
          description: "Advanced surge protection devices",
        },
        {
          name: "Residual Current Devices",
          href: "#",
          description: "Safety protection equipment",
        },
      ],
    },
    {
      name: "Power Distribution",
      items: [
        {
          name: "Distribution Boards",
          href: "#",
          description: "Modular distribution solutions",
        },
        {
          name: "Panel Boards",
          href: "#",
          description: "Custom panel configurations",
        },
        {
          name: "Bus Bar Systems",
          href: "#",
          description: "Efficient power distribution",
        },
        {
          name: "Power Meters",
          href: "#",
          description: "Advanced metering solutions",
        },
      ],
    },
    {
      name: "Industrial Controls",
      items: [
        {
          name: "Contactors",
          href: "#",
          description: "Reliable switching solutions",
        },
        {
          name: "Motor Protection",
          href: "#",
          description: "Complete motor safety systems",
        },
        {
          name: "PLCs & HMIs",
          href: "#",
          description: "Smart control solutions",
        },
        {
          name: "Sensors & Relays",
          href: "#",
          description: "Precision control devices",
        },
      ],
    },
  ],
  featured: [
    { name: "New Arrivals", href: "#", description: "Latest CHINT products" },
    { name: "Best Sellers", href: "#", description: "Most popular solutions" },
    { name: "Special Offers", href: "#", description: "Limited time deals" },
  ],
};

const services = [
  {
    name: "Residential",
    description: "Complete home electrical solutions",
    href: "#",
    items: [
      "Home Distribution Boards",
      "Safety Devices",
      "Smart Home Solutions",
      "Energy Meters",
    ],
  },
  {
    name: "Commercial",
    description: "Business & office solutions",
    href: "#",
    items: [
      "Building Management",
      "Lighting Control",
      "Power Management",
      "Safety Systems",
    ],
  },
  {
    name: "Industrial",
    description: "Heavy-duty industrial equipment",
    href: "#",
    items: [
      "Factory Automation",
      "Motor Control",
      "Power Distribution",
      "Process Control",
    ],
  },
  {
    name: "Infrastructure",
    description: "Large-scale project solutions",
    href: "#",
    items: [
      "Grid Solutions",
      "Railway Systems",
      "Smart City",
      "Renewable Energy",
    ],
  },
];

const resources = [
  {
    name: "Support",
    items: [
      { name: "Technical Documentation", href: "#" },
      { name: "Product Catalogs", href: "#" },
      { name: "Installation Guides", href: "#" },
      { name: "Video Tutorials", href: "#" },
    ],
  },
  {
    name: "Training",
    items: [
      { name: "Online Courses", href: "#" },
      { name: "Certification Programs", href: "#" },
      { name: "Workshops", href: "#" },
      { name: "Technical Seminars", href: "#" },
    ],
  },
  {
    name: "Resources",
    items: [
      { name: "Case Studies", href: "#" },
      { name: "White Papers", href: "#" },
      { name: "Industry News", href: "#" },
      { name: "Research Reports", href: "#" },
    ],
  },
];

export default function MegaMenu() {
  const [isScrolled, setIsScrolled] = React.useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = React.useState(false);
  const [expandedSection, setExpandedSection] = React.useState<string | null>(
    null
  );

  React.useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 0);
    };

    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  const mobileMenuVariants = {
    closed: {
      opacity: 0,
      x: "100%",
      transition: {
        type: "spring",
        stiffness: 400,
        damping: 40,
      },
    },
    open: {
      opacity: 1,
      x: "0%",
      transition: {
        type: "spring",
        stiffness: 400,
        damping: 40,
      },
    },
  };

  const contentVariants = {
    collapsed: {
      height: 0,
      opacity: 0,
      transition: {
        duration: 0.2,
        ease: "easeInOut",
      },
    },
    expanded: {
      height: "auto",
      opacity: 1,
      transition: {
        duration: 0.2,
        ease: "easeInOut",
      },
    },
  };

  const toggleSection = (section: string) => {
    setExpandedSection(expandedSection === section ? null : section);
  };

  const MobileSection = ({
    title,
    children,
  }: {
    title: string;
    children: React.ReactNode;
  }) => (
    <div className="border-b border-gray-200 py-4">
      <motion.button
        whileTap={{ scale: 0.98 }}
        onClick={() => toggleSection(title)}
        className="flex items-center justify-between w-full"
      >
        <span className="text-lg font-medium text-gray-900">{title}</span>
        <motion.div
          animate={{ rotate: expandedSection === title ? 180 : 0 }}
          transition={{ duration: 0.2 }}
        >
          <ChevronDown className="w-5 h-5 text-gray-500" />
        </motion.div>
      </motion.button>
      <AnimatePresence initial={false}>
        {expandedSection === title && (
          <motion.div
            initial="collapsed"
            animate="expanded"
            exit="collapsed"
            variants={contentVariants}
            className="overflow-hidden"
          >
            <div className="pt-4 pl-4">{children}</div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );

  return (
    <div
      className={`fixed top-0 left-0 right-0 transition-all duration-300 z-50 ${
        isScrolled || isMobileMenuOpen
          ? "bg-white/95 shadow-md"
          : "bg-transparent"
      }`}
    >
      <div className="max-w-7xl mx-auto">
        <div className="flex justify-between items-center px-4 py-6 sm:px-6 md:justify-start md:space-x-10">
          <div className="flex justify-start lg:w-0 lg:flex-1">
            <motion.a
              href="#"
              className="flex items-center space-x-2"
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
            >
              <Zap
                className={`w-8 h-8 ${
                  isScrolled || isMobileMenuOpen
                    ? "text-blue-600"
                    : "text-white"
                }`}
              />
              <span
                className={`text-2xl font-bold transition-colors ${
                  isScrolled || isMobileMenuOpen
                    ? "text-gray-900"
                    : "text-white"
                }`}
              >
                OMICRON
              </span>
            </motion.a>
          </div>

          <div className="hidden md:flex space-x-8">
            <a
              href="#"
              className={`transition-colors ${
                isScrolled
                  ? "text-gray-900 hover:text-blue-600"
                  : "text-white hover:text-blue-400"
              }`}
            >
              Home
            </a>
            <a
              href="#about"
              className={`transition-colors ${
                isScrolled
                  ? "text-gray-900 hover:text-blue-600"
                  : "text-white hover:text-blue-400"
              }`}
            >
              About
            </a>
            <Popover className="relative">
              {({ open }) => (
                <>
                  <Popover.Button
                    className={`
                      group inline-flex items-center text-base font-medium focus:outline-none
                      ${
                        open
                          ? "text-blue-600"
                          : isScrolled
                          ? "text-gray-900 hover:text-blue-600"
                          : "text-white hover:text-blue-400"
                      }
                    `}
                  >
                    <span>Products</span>
                    <ChevronDown
                      className={`ml-2 h-5 w-5 transition-colors ${
                        open ? "text-blue-600" : "group-hover:text-blue-400"
                      }`}
                      aria-hidden="true"
                    />
                  </Popover.Button>

                  <Transition
                    as={Fragment}
                    enter="transition ease-out duration-200"
                    enterFrom="opacity-0 -translate-y-1"
                    enterTo="opacity-100 translate-y-0"
                    leave="transition ease-in duration-150"
                    leaveFrom="opacity-100 translate-y-0"
                    leaveTo="opacity-0 -translate-y-1"
                  >
                    <Popover.Panel className="fixed left-0 right-0 z-40 mt-3">
                      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                        <div className="rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 overflow-hidden">
                          <div className="relative grid grid-cols-3 gap-6 bg-white px-5 py-6 sm:gap-8 sm:p-8">
                            {products.categories.map((category) => (
                              <div key={category.name}>
                                <h3 className="text-base font-medium text-gray-900 mb-4">
                                  {category.name}
                                </h3>
                                <ul className="space-y-4">
                                  {category.items.map((item) => (
                                    <li key={item.name}>
                                      <a
                                        href={item.href}
                                        className="group flex items-start space-x-3"
                                      >
                                        <ChevronRight className="h-5 w-5 text-blue-600 group-hover:text-blue-800" />
                                        <div>
                                          <p className="text-base font-medium text-gray-900 group-hover:text-blue-600">
                                            {item.name}
                                          </p>
                                          <p className="mt-1 text-sm text-gray-500 group-hover:text-gray-900">
                                            {item.description}
                                          </p>
                                        </div>
                                      </a>
                                    </li>
                                  ))}
                                </ul>
                              </div>
                            ))}
                          </div>
                          <div className="bg-gray-50 px-5 py-5 sm:px-8 sm:py-8">
                            <div>
                              <h3 className="text-base font-medium text-gray-900">
                                Featured
                              </h3>
                              <ul className="mt-4 space-y-4">
                                {products.featured.map((item) => (
                                  <li key={item.name} className="truncate">
                                    <a
                                      href={item.href}
                                      className="group flex items-center space-x-3"
                                    >
                                      <ChevronRight className="h-5 w-5 text-blue-600 group-hover:text-blue-800" />
                                      <div>
                                        <p className="text-base font-medium text-gray-900 group-hover:text-blue-600">
                                          {item.name}
                                        </p>
                                        <p className="mt-1 text-sm text-gray-500 group-hover:text-gray-900">
                                          {item.description}
                                        </p>
                                      </div>
                                    </a>
                                  </li>
                                ))}
                              </ul>
                            </div>
                          </div>
                        </div>
                      </div>
                    </Popover.Panel>
                  </Transition>
                </>
              )}
            </Popover>

            <Popover className="relative">
              {({ open }) => (
                <>
                  <Popover.Button
                    className={`
                      group inline-flex items-center text-base font-medium focus:outline-none
                      ${
                        open
                          ? "text-blue-600"
                          : isScrolled
                          ? "text-gray-900 hover:text-blue-600"
                          : "text-white hover:text-blue-400"
                      }
                    `}
                  >
                    <span>Services</span>
                    <ChevronDown
                      className={`ml-2 h-5 w-5 transition-colors ${
                        open ? "text-blue-600" : "group-hover:text-blue-400"
                      }`}
                      aria-hidden="true"
                    />
                  </Popover.Button>

                  <Transition
                    as={Fragment}
                    enter="transition ease-out duration-200"
                    enterFrom="opacity-0 -translate-y-1"
                    enterTo="opacity-100 translate-y-0"
                    leave="transition ease-in duration-150"
                    leaveFrom="opacity-100 translate-y-0"
                    leaveTo="opacity-0 -translate-y-1"
                  >
                    <Popover.Panel className="fixed left-0 right-0 z-40 mt-3">
                      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                        <div className="rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 overflow-hidden">
                          <div className="relative grid grid-cols-4 gap-6 bg-white px-5 py-6 sm:gap-8 sm:p-8">
                            {services.map((service) => (
                              <div key={service.name} className="p-4">
                                <h3 className="text-base font-medium text-gray-900 mb-2">
                                  {service.name}
                                </h3>
                                <p className="text-sm text-gray-500 mb-4">
                                  {service.description}
                                </p>
                                <ul className="space-y-3">
                                  {service.items.map((item) => (
                                    <li
                                      key={item}
                                      className="flex items-center space-x-2"
                                    >
                                      <ChevronRight className="h-4 w-4 text-blue-600" />
                                      <span className="text-sm text-gray-600 hover:text-blue-600">
                                        {item}
                                      </span>
                                    </li>
                                  ))}
                                </ul>
                              </div>
                            ))}
                          </div>
                        </div>
                      </div>
                    </Popover.Panel>
                  </Transition>
                </>
              )}
            </Popover>

            <Popover className="relative">
              {({ open }) => (
                <>
                  <Popover.Button
                    className={`
                      group inline-flex items-center text-base font-medium focus:outline-none
                      ${
                        open
                          ? "text-blue-600"
                          : isScrolled
                          ? "text-gray-900 hover:text-blue-600"
                          : "text-white hover:text-blue-400"
                      }
                    `}
                  >
                    <span>Resources</span>
                    <ChevronDown
                      className={`ml-2 h-5 w-5 transition-colors ${
                        open ? "text-blue-600" : "group-hover:text-blue-400"
                      }`}
                      aria-hidden="true"
                    />
                  </Popover.Button>

                  <Transition
                    as={Fragment}
                    enter="transition ease-out duration-200"
                    enterFrom="opacity-0 -translate-y-1"
                    enterTo="opacity-100 translate-y-0"
                    leave="transition ease-in duration-150"
                    leaveFrom="opacity-100 translate-y-0"
                    leaveTo="opacity-0 -translate-y-1"
                  >
                    <Popover.Panel className="fixed left-0 right-0 z-40 mt-3">
                      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                        <div className="rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 overflow-hidden">
                          <div className="relative grid grid-cols-3 gap-6 bg-white px-5 py-6 sm:gap-8 sm:p-8">
                            {resources.map((section) => (
                              <div key={section.name}>
                                <h3 className="text-base font-medium text-gray-900 mb-4">
                                  {section.name}
                                </h3>
                                <ul className="space-y-4">
                                  {section.items.map((item) => (
                                    <li key={item.name}>
                                      <a
                                        href={item.href}
                                        className="group flex items-center space-x-3"
                                      >
                                        <ChevronRight className="h-5 w-5 text-blue-600 group-hover:text-blue-800" />
                                        <span className="text-base text-gray-900 group-hover:text-blue-600">
                                          {item.name}
                                        </span>
                                      </a>
                                    </li>
                                  ))}
                                </ul>
                              </div>
                            ))}
                          </div>
                        </div>
                      </div>
                    </Popover.Panel>
                  </Transition>
                </>
              )}
            </Popover>

            <a
              href="#about"
              className={`transition-colors ${
                isScrolled
                  ? "text-gray-900 hover:text-blue-600"
                  : "text-white hover:text-blue-400"
              }`}
            >
              About
            </a>
            <a
              href="#contact"
              className={`transition-colors ${
                isScrolled
                  ? "text-gray-900 hover:text-blue-600"
                  : "text-white hover:text-blue-400"
              }`}
            >
              Contact
            </a>
          </div>

          <div className="flex md:hidden">
            <motion.button
              whileTap={{ scale: 0.95 }}
              onClick={() => {
                setIsMobileMenuOpen(!isMobileMenuOpen);
                setExpandedSection(null);
              }}
              className={`p-2 rounded-md ${
                isScrolled || isMobileMenuOpen
                  ? "text-gray-600 hover:text-gray-900"
                  : "text-white hover:text-gray-200"
              }`}
            >
              {isMobileMenuOpen ? (
                <X className="h-6 w-6" />
              ) : (
                <MenuIcon className="h-6 w-6" />
              )}
            </motion.button>
          </div>

          <div className="hidden md:flex items-center justify-end md:flex-1 lg:w-0">
            <motion.button
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              className="ml-8 whitespace-nowrap inline-flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-base font-medium text-white bg-blue-600 hover:bg-blue-700"
            >
              Get Quote
            </motion.button>
          </div>
        </div>
      </div>

      <AnimatePresence>
        {isMobileMenuOpen && (
          <motion.div
            initial="closed"
            animate="open"
            exit="closed"
            variants={mobileMenuVariants}
            className="fixed inset-y-0 right-0 w-full bg-white shadow-xl md:hidden overflow-y-auto"
          >
            <div className="px-4 py-6">
              <MobileSection title="Products">
                {products.categories.map((category) => (
                  <div key={category.name} className="mb-4">
                    <h4 className="text-sm font-semibold text-gray-500 mb-2">
                      {category.name}
                    </h4>
                    <ul className="space-y-2">
                      {category.items.map((item) => (
                        <motion.li key={item.name} whileTap={{ scale: 0.98 }}>
                          <a
                            href={item.href}
                            className="flex items-center space-x-2 text-gray-600 hover:text-blue-600"
                          >
                            <ChevronRight className="h-4 w-4" />
                            <span className="text-sm">{item.name}</span>
                          </a>
                        </motion.li>
                      ))}
                    </ul>
                  </div>
                ))}
              </MobileSection>

              <MobileSection title="Solutions">
                {services.map((service) => (
                  <div key={service.name} className="mb-4">
                    <h4 className="text-sm font-semibold text-gray-500 mb-2">
                      {service.name}
                    </h4>
                    <ul className="space-y-2">
                      {service.items.map((item) => (
                        <motion.li key={item} whileTap={{ scale: 0.98 }}>
                          <a
                            href="#"
                            className="flex items-center space-x-2 text-gray-600 hover:text-blue-600"
                          >
                            <ChevronRight className="h-4 w-4" />
                            <span className="text-sm">{item}</span>
                          </a>
                        </motion.li>
                      ))}
                    </ul>
                  </div>
                ))}
              </MobileSection>

              <MobileSection title="Resources">
                {resources.map((section) => (
                  <div key={section.name} className="mb-4">
                    <h4 className="text-sm font-semibold text-gray-500 mb-2">
                      {section.name}
                    </h4>
                    <ul className="space-y-2">
                      {section.items.map((item) => (
                        <motion.li key={item.name} whileTap={{ scale: 0.98 }}>
                          <a
                            href={item.href}
                            className="flex items-center space-x-2 text-gray-600 hover:text-blue-600"
                          >
                            <ChevronRight className="h-4 w-4" />
                            <span className="text-sm">{item.name}</span>
                          </a>
                        </motion.li>
                      ))}
                    </ul>
                  </div>
                ))}
              </MobileSection>

              <MobileSection title="Quick Links">
                <ul className="space-y-2">
                  {["About", "Contact"].map((item) => (
                    <motion.li key={item} whileTap={{ scale: 0.98 }}>
                      <a
                        href={`#${item.toLowerCase()}`}
                        className="flex items-center space-x-2 text-gray-600 hover:text-blue-600"
                      >
                        <ChevronRight className="h-4 w-4" />
                        <span className="text-sm">{item}</span>
                      </a>
                    </motion.li>
                  ))}
                </ul>
              </MobileSection>

              <div className="mt-6">
                <motion.button
                  whileHover={{ scale: 1.02 }}
                  whileTap={{ scale: 0.98 }}
                  className="w-full flex items-center justify-center px-4 py-3 border border-transparent rounded-md shadow-sm text-base font-medium text-white bg-blue-600 hover:bg-blue-700"
                >
                  Get Quote
                </motion.button>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
