"use client";

import React, { useEffect, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { HeaderData, MenuItem, TopBarData } from "@/types/navigation";
import { X, ChevronDown, ShoppingBag } from "lucide-react";
import { Logo } from "@/components/common/Logo";

interface MobileMenuProps {
  isOpen: boolean;
  onClose: () => void;
  menuItems: MenuItem[];
  topBarData: TopBarData;
  ctaData: HeaderData["cta"];
}

export const MobileMenu: React.FC<MobileMenuProps> = ({
  isOpen,
  onClose,
  menuItems,
  topBarData,
  ctaData,
}) => {
  const [expandedItem, setExpandedItem] = useState<string | null>(null);
  const [expandedSubCategory, setExpandedSubCategory] = useState<string | null>(null);

  // Real live behavior has no Escape handler at all (custom.js has none for
  // any menu/search panel) — added here as a genuine accessibility fix, not
  // a live-parity item, same call already made for the search dropdown.
  useEffect(() => {
    if (!isOpen) return;
    const onEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    document.addEventListener("keydown", onEscape);
    return () => document.removeEventListener("keydown", onEscape);
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 lg:hidden flex">
      {/* Backdrop — real `.menu-overlay.active`: rgba(0,0,0,0.8), 0.4s fade */}
      <div
        className="header-mobile-overlay fixed inset-0 opacity-100"
        onClick={onClose}
        aria-hidden="true"
      />

      {/* Drawer Content — real `.menu` on mobile: fixed, width 80%, white bg */}
      <div className="relative w-4/5 max-w-sm bg-white h-full shadow-2xl flex flex-col z-10 overflow-hidden animate-in slide-in-from-left duration-300">
        {/* Top Header inside Drawer */}
        <div className="p-4 border-b border-slate-100 flex items-center justify-between bg-slate-50">
          <Logo />
          <button
            onClick={onClose}
            className="p-2 text-slate-500 hover:text-slate-900 rounded-full hover:bg-slate-200/60 transition-colors"
            aria-label="Close menu"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Scrollable Navigation List */}
        <div className="flex-1 overflow-y-auto p-4 space-y-2">
          {menuItems.map((item) => {
            const isExpanded = expandedItem === item.id;
            return (
              <div key={item.id} className="border-b border-slate-100 pb-2">
                {item.hasSubmenu ? (
                  <div>
                    <button
                      onClick={() => setExpandedItem(isExpanded ? null : item.id)}
                      className="w-full flex items-center justify-between py-2 text-slate-800 font-bold text-sm text-left hover:text-[#5C7A36]"
                    >
                      <span>{item.label}</span>
                      <ChevronDown
                        className={`w-4 h-4 text-slate-400 transition-transform ${
                          isExpanded ? "rotate-180 text-[#5C7A36]" : ""
                        }`}
                      />
                    </button>

                    {/* Collapsible Content */}
                    {isExpanded && (
                      <div className="pl-3 mt-1 space-y-2 text-xs border-l-2 border-green-200">
                        {/* Mega Menu Categories */}
                        {item.isMegaMenu && item.categories ? (
                          item.categories.map((cat) => {
                            const isCatExpanded = expandedSubCategory === cat.categoryTitle;
                            return (
                              <div key={cat.categoryTitle} className="space-y-1">
                                <button
                                  onClick={() =>
                                    setExpandedSubCategory(
                                      isCatExpanded ? null : cat.categoryTitle
                                    )
                                  }
                                  className="w-full flex items-center justify-between py-1.5 font-semibold text-slate-700 hover:text-[#5C7A36]"
                                >
                                  <span>{cat.categoryTitle}</span>
                                  <ChevronDown
                                    className={`w-3.5 h-3.5 transition-transform ${
                                      isCatExpanded ? "rotate-180" : ""
                                    }`}
                                  />
                                </button>
                                {isCatExpanded && (
                                  <div className="pl-3 space-y-1.5 py-1 text-slate-600">
                                    {cat.items.map((sub) => (
                                      <Link
                                        key={sub.href}
                                        href={sub.href}
                                        onClick={onClose}
                                        className="block py-1 hover:text-[#5C7A36] font-medium"
                                      >
                                        {sub.label}
                                      </Link>
                                    ))}
                                  </div>
                                )}
                              </div>
                            );
                          })
                        ) : (
                          /* Standard Subitems */
                          item.subItems?.map((sub) => (
                            <Link
                              key={sub.href}
                              href={sub.href}
                              onClick={onClose}
                              className="block py-1.5 font-medium text-slate-700 hover:text-[#5C7A36]"
                            >
                              {sub.label}
                            </Link>
                          ))
                        )}
                      </div>
                    )}
                  </div>
                ) : (
                  <Link
                    href={item.href}
                    onClick={onClose}
                    className="block py-2 text-slate-800 font-bold text-sm hover:text-[#5C7A36]"
                  >
                    {item.label}
                  </Link>
                )}
              </div>
            );
          })}
        </div>

        {/* Drawer Bottom Actions — real `.order_btn`/`.login-new` styling, no fabricated "Earn Online" (not part of the live header) */}
        <div className="p-4 bg-slate-50 border-t border-slate-100 space-y-3">
          <a
            href={ctaData.orderNowUrl}
            onClick={onClose}
            className="header-order-pulse flex items-center justify-center gap-1.5 w-full text-sm font-bold text-white bg-[#f58e0e] hover:bg-[#e78e21] px-3 py-2.5 rounded-full transition-colors"
          >
            <ShoppingBag className="w-4 h-4" />
            <span>Order Now</span>
          </a>

          <a
            href={ctaData.loginUrl}
            onClick={onClose}
            className="flex items-center justify-center w-full text-sm font-bold text-white px-3 py-2.5 rounded-[3px]"
            style={{ background: "linear-gradient(96.16deg, #456228 11.84%, #5F8F2D 97.09%)" }}
          >
            Login
          </a>

          {/* Real `.affiliate-btn` (mod_menu/default.php) — confirmed live element */}
          <a
            href={ctaData.earnOnlineUrl}
            onClick={onClose}
            className="header-shine-btn flex items-center justify-center gap-1.5 w-full text-sm font-semibold text-white px-3 py-2.5 rounded-[5px]"
            style={{ background: "linear-gradient(90deg, #639E15 0%, #506634 100%)" }}
          >
            <span>Earn Online</span>
          </a>

          <div className="space-y-1.5 text-xs text-slate-600">
            <a
              href={topBarData.whatsappUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-2 text-emerald-600 font-bold"
            >
              <Image src="/icons/whatsapp.svg" alt="" width={16} height={16} className="w-4 h-4" />
              <span>WhatsApp: {topBarData.whatsappNumber}</span>
            </a>
            <a href={`tel:${topBarData.phone}`} className="flex items-center gap-2">
              <Image src="/icons/phone-dark.svg" alt="" width={14} height={14} className="w-3.5 h-3.5" />
              <span>{topBarData.phone}</span>
            </a>
            <a href={`mailto:${topBarData.email}`} className="flex items-center gap-2">
              <Image src="/icons/mail-dark.svg" alt="" width={16} height={13} className="w-4 h-[13px]" />
              <span>{topBarData.email}</span>
            </a>
          </div>
        </div>
      </div>
    </div>
  );
};
