"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";
import { useRouter, usePathname } from "next/navigation";
import { 
  ShoppingBag, 
  Search, 
  Heart, 
  User, 
  Menu, 
  X,
  ArrowRight
} from "lucide-react";
import { getCart } from "@/lib/cart";
import SearchBar from "./SearchBar";
import { useCurrency } from "@/providers/CurrencyProvider";
import { useSettings } from "@/providers/SettingsProvider";

interface Category {
  id: string;
  name: string;
  slug: string;
}

interface HeaderProps {
  categories?: Category[];
}

function MegaMenuContent({ categories }: { categories: Category[] }) {
  const col1 = categories.slice(0, 6);
  const col2 = categories.slice(6, 12);
  const col3 = categories.slice(12, 18);
  const col4 = categories.slice(18, 24);

  return (
    <div className="max-w-[1600px] mx-auto px-8 py-6 flex justify-between gap-8 min-w-[1260px]">
      {/* Left Link Columns Container */}
      <div className="flex gap-12 xl:gap-20">
        {col1.length > 0 && (
          <div className="flex flex-col gap-8 w-48">
            <div>
              <h3 className="font-extrabold text-zinc-950 mb-4 text-[13px]">Top Categories</h3>
              <ul className="space-y-3.5 text-zinc-500 text-[13px]">
                {col1.map(c => (
                  <li key={c.id}><Link href={`/category/${c.slug}`} className="hover:text-zinc-950 transition-colors">{c.name}</Link></li>
                ))}
              </ul>
            </div>
          </div>
        )}

        {col2.length > 0 && (
          <div className="flex flex-col gap-8 w-48">
            <div>
              <h3 className="font-extrabold text-zinc-950 mb-4 text-[13px]">More Categories</h3>
              <ul className="space-y-3.5 text-zinc-500 text-[13px]">
                {col2.map(c => (
                  <li key={c.id}><Link href={`/category/${c.slug}`} className="hover:text-zinc-950 transition-colors">{c.name}</Link></li>
                ))}
              </ul>
            </div>
          </div>
        )}

        {col3.length > 0 && (
          <div className="flex flex-col gap-8 w-48">
            <div>
              <h3 className="font-extrabold text-zinc-950 mb-4 text-[13px]">Explore</h3>
              <ul className="space-y-3.5 text-zinc-500 text-[13px]">
                {col3.map(c => (
                  <li key={c.id}><Link href={`/category/${c.slug}`} className="hover:text-zinc-950 transition-colors">{c.name}</Link></li>
                ))}
              </ul>
            </div>
          </div>
        )}

        {col4.length > 0 && (
          <div className="flex flex-col gap-8 w-48">
            <div>
              <h3 className="font-extrabold text-zinc-950 mb-4 text-[13px]">Discover</h3>
              <ul className="space-y-3.5 text-zinc-500 text-[13px]">
                {col4.map(c => (
                  <li key={c.id}><Link href={`/category/${c.slug}`} className="hover:text-zinc-950 transition-colors">{c.name}</Link></li>
                ))}
              </ul>
            </div>
          </div>
        )}
      </div>

      {/* Right Image Container */}
      <div className="w-[380px] xl:w-[450px] shrink-0">
        <Link href="/shop" className="block relative w-full aspect-[4/5] group/image overflow-hidden bg-zinc-100">
          <Image 
            src="https://placehold.co/600x800/e2e8f0/64748b.png?text=Store+Image" 
            alt="Shop All" 
            fill
            className="object-cover group-hover/image:scale-105 transition-transform duration-700 ease-out" 
          />
          <div className="absolute inset-0 flex items-center justify-center bg-black/20">
            <span className="text-white text-2xl xl:text-3xl font-black tracking-wide drop-shadow-lg text-center px-4">
              Shop New Arrivals
            </span>
          </div>
        </Link>
      </div>
    </div>
  );
}

export default function Header({ categories: initialCategories }: HeaderProps) {
  const router = useRouter();
  const pathname = usePathname();
  const { storeName, settings } = useSettings();
  const [categories, setCategories] = useState<Category[]>(initialCategories || []);
  const [cartItemsCount, setCartItemsCount] = useState(0);
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [isSearchOpen, setIsSearchOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  
  // Brand Settings State
  const [brandLogoUrl, setBrandLogoUrl] = useState("");
  const [brandSlogan, setBrandSlogan] = useState("Tall Men 6' - 7'1\" | Tall Women 5'9\" - 6'6\"");

  const { currencies, selectedCurrency, setCurrency } = useCurrency();

  // Fetch categories if not passed as prop
  useEffect(() => {
    if (initialCategories && initialCategories.length > 0) {
      setCategories(initialCategories);
      return;
    }

    const fetchCategories = async () => {
      try {
        const res = await fetch("/api/categories");
        if (res.ok) {
          const data = await res.json();
          setCategories(data);
        }
      } catch (err) {
        console.error("Failed to fetch header categories:", err);
      }
    };
    fetchCategories();
  }, [initialCategories]);

  // Fetch brand settings
  useEffect(() => {
    const fetchBrandSettings = async () => {
      try {
        const res = await fetch("/api/admin/settings");
        if (res.ok) {
          const data = await res.json();
          if (data.brand_logo_url) setBrandLogoUrl(data.brand_logo_url);
          if (data.brand_slogan) setBrandSlogan(data.brand_slogan);
        }
      } catch (err) {
        console.error("Failed to fetch brand settings:", err);
      }
    };
    fetchBrandSettings();

    // Listen for real-time updates when saving from admin
    const handleUpdate = () => fetchBrandSettings();
    window.addEventListener("brand-settings-updated", handleUpdate);
    return () => window.removeEventListener("brand-settings-updated", handleUpdate);
  }, []);

  // Sync cart count
  useEffect(() => {
    const updateCartCount = () => {
      const cart = getCart();
      const count = cart.reduce((sum, item) => sum + item.quantity, 0);
      setCartItemsCount(count);
    };

    updateCartCount();
    window.addEventListener("cart-updated", updateCartCount);
    window.addEventListener("storage", updateCartCount);

    return () => {
      window.removeEventListener("cart-updated", updateCartCount);
      window.removeEventListener("storage", updateCartCount);
    };
  }, []);

  // Close menus on page transition
  useEffect(() => {
    setIsMenuOpen(false);
    setIsSearchOpen(false);
  }, [pathname]);

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (searchQuery.trim()) {
      router.push(`/shop?query=${encodeURIComponent(searchQuery.trim())}`);
      setIsSearchOpen(false);
      setSearchQuery("");
    }
  };

  return (
    <>
      {/* 1. TOP UTILITY BAR */}
      <div className="w-full bg-zinc-50 text-zinc-800 py-2 px-4 text-[10px] sm:text-[11px] font-medium tracking-wide border-b border-zinc-200 z-50 relative flex justify-between items-center">
        <div className="hidden md:flex flex-1"></div>
        <div className="flex-1 text-center whitespace-nowrap">
          {brandSlogan}
        </div>
        <div className="hidden md:flex flex-1 justify-end items-center space-x-6">
          <div className="flex items-center gap-2">
            <span className="font-bold">CURRENCY</span>
            <select
              value={selectedCurrency?.code}
              onChange={(e) => setCurrency(e.target.value)}
              className="bg-transparent text-zinc-500 font-bold focus:outline-none cursor-pointer border-none"
            >
              {currencies.map(c => (
                <option key={c.code} value={c.code} className="text-black">
                  {c.code} ({c.symbol})
                </option>
              ))}
            </select>
          </div>
          <Link href="/help" className="hover:text-zinc-500 transition-colors font-bold">HELP</Link>
        </div>
      </div>

      {/* 2. PREMIUM NAVIGATION HEADER */}
      <header className="sticky top-0 z-50 w-full bg-white border-b border-zinc-150 transition-all duration-300">
        <div className="max-w-[1600px] mx-auto px-6 lg:px-8 h-14 flex items-center justify-between">
          
          {/* Menu Icon (Mobile) */}
          <button 
            onClick={() => setIsMenuOpen(true)}
            className="lg:hidden p-2 text-zinc-700 hover:text-black transition-colors cursor-pointer"
            aria-label="Open Menu"
          >
            <Menu className="w-6 h-6" />
          </button>

          {/* Navigation Links (Left side - to balance the layout like screenshot) */}
          <nav className="hidden lg:flex items-center h-full space-x-6 xl:space-x-8 flex-1">
            {/* SHOP MEGA MENU */}
            <div className="group/men h-full flex items-center">
              <Link href="/shop" className="text-[13px] font-semibold text-zinc-500 hover:text-zinc-950 h-full flex items-center border-b-2 border-transparent group-hover/men:border-zinc-950 transition-colors">
                Shop All
              </Link>
              
              {/* Dropdown Container */}
              <div className="absolute left-0 top-full w-full bg-white shadow-xl opacity-0 invisible group-hover/men:opacity-100 group-hover/men:visible transition-all duration-200 z-[100] border-t border-zinc-100 pb-12 cursor-default overflow-x-auto scrollbar-thin">
                <MegaMenuContent categories={categories} />
              </div>
            </div>

            <Link href="/gift-cards" className="text-[13px] font-semibold text-zinc-500 hover:text-zinc-950 h-full flex items-center">
              Gift Cards
            </Link>
            <Link href="/about" className="text-[13px] font-semibold text-zinc-500 hover:text-zinc-950 h-full flex items-center">
              About
            </Link>
          </nav>

          {/* Logo */}
          <div className="flex-1 flex justify-center">
            <Link 
              href="/" 
              className="hover:opacity-90 transition-opacity flex-shrink-0"
            >
              {brandLogoUrl ? (
                <div className="relative h-6 sm:h-8 w-32">
                  <Image src={brandLogoUrl} alt={storeName} fill className="object-contain" />
                </div>
              ) : (
                <div className="text-xl sm:text-2xl font-black tracking-[0.25em] text-zinc-950">
                  LOGO
                </div>
              )}
            </Link>
          </div>

          {/* Right Header Icons */}
          <div className="flex items-center justify-end space-x-3 sm:space-x-5 flex-1">
            <div className="hidden xl:flex items-center mr-2">
               <SearchBar />
            </div>

            <button 
              onClick={() => setIsSearchOpen(!isSearchOpen)}
              className="xl:hidden p-2 text-zinc-700 hover:text-zinc-950 transition-all cursor-pointer" 
              aria-label="Search"
            >
              <Search className="w-5 h-5" />
            </button>
            <button 
              onClick={() => router.push("/wishlist")}
              className="hidden sm:block p-2 text-zinc-700 hover:text-zinc-950 transition-all cursor-pointer" 
              aria-label="Wishlist"
            >
              <Heart className="w-5 h-5" />
            </button>
            <button 
              onClick={() => router.push("/account")}
              className="p-2 text-zinc-700 hover:text-zinc-950 transition-all cursor-pointer" 
              aria-label="Account"
            >
              <User className="w-5 h-5" />
            </button>
            <Link 
              href="/cart" 
              className="p-2 text-zinc-700 hover:text-zinc-950 transition-all relative" 
              aria-label="Cart"
            >
              <ShoppingBag className="w-5 h-5" />
              {cartItemsCount > 0 && (
                <span className="absolute top-1 right-1 w-4 h-4 bg-zinc-950 text-white text-[8px] font-black rounded-full flex items-center justify-center border border-white">
                  {cartItemsCount}
                </span>
              )}
            </Link>
          </div>

        </div>

        {/* Dynamic Slide-down Search Bar */}
        {isSearchOpen && (
          <div className="xl:hidden border-t border-zinc-150 bg-zinc-50 py-4 px-6 animate-in slide-in-from-top duration-200">
            <form onSubmit={handleSearchSubmit} className="max-w-3xl mx-auto flex items-center border border-zinc-300 rounded-sm bg-white overflow-hidden shadow-sm">
              <input 
                type="text" 
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search..." 
                className="flex-1 px-4 py-3 text-xs sm:text-sm bg-transparent outline-none text-zinc-850 placeholder-zinc-400"
                autoFocus
              />
              <button 
                type="submit"
                className="bg-zinc-950 hover:bg-zinc-800 text-white px-6 py-3 text-xs font-bold uppercase tracking-widest transition-colors cursor-pointer"
              >
                Search
              </button>
            </form>
          </div>
        )}
      </header>

      {/* Slide-out Mobile Navigation Drawer */}
      {isMenuOpen && (
        <div className="fixed inset-0 z-[100] flex">
          {/* Overlay */}
          <div
            className="fixed inset-0 bg-black/60 backdrop-blur-xs transition-opacity duration-300"
            onClick={() => setIsMenuOpen(false)}
          />

          {/* Sidebar content */}
          <div className="relative w-80 max-w-[85vw] bg-white h-full flex flex-col shadow-2xl z-10 animate-in slide-in-from-left duration-300">
            {/* Header */}
            <div className="flex items-center justify-between border-b border-zinc-100 px-6 py-5 shrink-0">
              <span className="text-sm font-black tracking-widest uppercase">{storeName}</span>
              <button
                onClick={() => setIsMenuOpen(false)}
                className="p-1 text-zinc-500 hover:text-zinc-950 cursor-pointer"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Scrollable nav */}
            <nav className="flex-1 overflow-y-auto px-6 py-4 space-y-1">

              {/* Home */}
              <Link
                href="/"
                className="block text-[11px] font-bold tracking-widest uppercase text-zinc-800 hover:text-zinc-950 py-3 border-b border-zinc-100"
              >
                Home
              </Link>



              {/* --- Dynamic API categories (if any) --- */}
              {categories.length > 0 && (
                <div className="pt-4 pb-1">
                  <p className="text-[10px] font-extrabold tracking-widest uppercase text-zinc-400 mb-2">Categories</p>
                  {categories.map((cat) => (
                    <Link
                      key={cat.id}
                      href={`/category/${cat.slug}`}
                      className="block text-[12px] font-medium text-zinc-700 hover:text-zinc-950 py-2.5 border-b border-zinc-100 transition-colors"
                    >
                      {cat.name}
                    </Link>
                  ))}
                </div>
              )}

              {/* Shop All */}
              <Link
                href="/shop"
                className="flex items-center justify-between text-[11px] font-bold tracking-widest uppercase text-zinc-800 hover:text-zinc-950 py-3 border-b border-zinc-100 mt-2"
              >
                Shop All
                <ArrowRight className="w-4 h-4" />
              </Link>

              {/* Account */}
              <Link
                href="/account"
                className="flex items-center gap-2 text-[11px] font-black tracking-widest uppercase text-zinc-800 hover:text-zinc-950 py-3 border-b border-zinc-100"
              >
                <User className="w-4 h-4" />
                My Account
              </Link>

              {/* Admin */}
              <Link
                href="/admin"
                className="flex items-center gap-2 text-[11px] font-black tracking-widest uppercase text-red-600 hover:text-red-800 py-3"
              >
                <span className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse" />
                Admin Panel
              </Link>
            </nav>

            {/* Footer */}
            <div className="border-t border-zinc-100 px-6 py-5 shrink-0">
              <span className="text-[10px] text-zinc-400 font-bold uppercase tracking-widest block mb-2">Need help?</span>
              <a href={`mailto:${settings["contact_email"] || "support@store.local"}`} className="text-xs text-zinc-600 hover:text-zinc-950 transition-colors">
                {settings["contact_email"] || "support@store.local"}
              </a>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
