import { BUNDLES_ENABLED } from '@/lib/features';
import React, { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/router';
import MobileMenu from './MobileMenu';
import SearchDropdown from './SearchDropdown';
import { useCart } from '../context/CartContext';
import { useAuth } from '../context/AuthContext';

interface Brand {
  id: number;
  name: string;
  slug: string;
}

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

interface MenuItem {
  label: string;
  href?: string;
  tone?: 'sale' | 'gold';
  items?: { label: string; href: string }[];
}

interface StoreHeaderProps {
  onHoverChange?: (isHovering: boolean) => void;
}

const StoreHeader: React.FC<StoreHeaderProps> = ({ onHoverChange }) => {
  const router = useRouter();
  const { getTotalItems } = useCart();
  const { isAuthenticated, user } = useAuth();
  const [menuOpen, setMenuOpen] = useState(false);
  const [searchPanelOpen, setSearchPanelOpen] = useState(false);
  const [search, setSearch] = useState('');
  const [activeDropdown, setActiveDropdown] = useState<string | null>(null);
  const [brands, setBrands] = useState<Brand[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [scrolled, setScrolled] = useState(false);

  useEffect(() => {
    const update = () => setScrolled(window.scrollY > 24);
    update();
    window.addEventListener('scroll', update, { passive: true });
    return () => window.removeEventListener('scroll', update);
  }, []);

  useEffect(() => {
    const loadNavigation = async () => {
      try {
        const [brandsResponse, categoriesResponse] = await Promise.all([
          fetch('/api/brands'),
          fetch('/api/categories'),
        ]);
        setBrands(brandsResponse.ok ? await brandsResponse.json() : []);
        setCategories(categoriesResponse.ok ? await categoriesResponse.json() : []);
      } catch {
        setBrands([]);
        setCategories([]);
      }
    };
    void loadNavigation();
  }, []);

  const menuItems = useMemo<MenuItem[]>(() => [
    {
      label: 'Celé parfémy',
      items: categories.map((category) => ({ label: category.name, href: `/parfemy/${category.slug}` })),
    },
    {
      label: 'Značky',
      items: [
        { label: 'Všechny značky', href: '/brands' },
        ...brands.map((brand) => ({ label: brand.name, href: `/brands/${brand.slug}` })),
      ],
    },
    { label: 'Výprodej', href: '/vyprodej', tone: 'sale' },
    ...(BUNDLES_ENABLED ? [{ label: 'Výhodné sady', href: '/vyhodne-sady' }] : []),
    { label: 'Dárkové poukazy', href: '/darkove-poukazy' },
  ], [brands, categories]);

  const transparent = router.pathname === '/' && !scrolled;
  const actionLabel = 'hidden text-xs font-medium leading-none tracking-[0.02em] xl:block';

  return (
    <>
      <header
        className={`fixed left-0 right-0 top-[30px] z-50 transition-all duration-300 ${
          transparent
            ? 'bg-gradient-to-b from-black/65 to-black/10'
            : 'bg-luxury-dark/95 shadow-xl shadow-black/20 backdrop-blur-xl'
        }`}
      >
        <div className="mx-auto grid h-[70px] w-full max-w-[1600px] grid-cols-[40px_minmax(0,1fr)_136px] items-center px-3 sm:px-5 lg:h-[84px] lg:grid-cols-[1fr_auto_1fr] lg:px-[4vw]">
          <button
            type="button"
            onClick={() => setMenuOpen(true)}
            className="flex h-10 w-10 items-center justify-center text-luxury-light transition-colors hover:text-luxury-gold lg:hidden"
            aria-label="Otevřít menu"
          >
            <MenuIcon />
          </button>

          <Link href="/" className="flex min-w-0 items-center gap-2 justify-self-center lg:justify-self-start" aria-label="Vystříkejto.cz domů">
            <img src="/images/logo.png" alt="" className="h-11 w-11 flex-none object-contain lg:h-[62px] lg:w-[62px]" />
            <span className="flex min-w-0 flex-col items-start gap-0.5 leading-none">
              <strong className="whitespace-nowrap text-xs font-black tracking-[0.1em] text-luxury-gold sm:text-[13px] lg:text-[18px] lg:tracking-[0.13em]">
                VYSTŘÍKEJ TO
              </strong>
              <small className="whitespace-nowrap text-[8px] font-medium tracking-[0.06em] text-luxury-light/65 sm:text-[9px] lg:text-[11px]">
                Celé parfémy
              </small>
            </span>
          </Link>

          <nav className="hidden items-center gap-[clamp(14px,1.35vw,26px)] whitespace-nowrap lg:flex" aria-label="Hlavní navigace">
            {menuItems.map((item) => {
              const tone = item.tone === 'sale'
                ? 'text-[#ff4548] hover:text-[#ff6b6d]'
                : item.tone === 'gold'
                ? 'text-luxury-gold hover:text-yellow-300'
                : 'text-luxury-light hover:text-luxury-gold';
              const size = item.tone === 'sale'
                ? 'text-[clamp(13px,1.08vw,16px)] font-black'
                : 'text-[clamp(12px,1vw,15px)] font-bold';
              const shared = `relative flex items-center gap-1.5 rounded-md py-2 uppercase tracking-[0.035em] transition-colors focus:outline-none focus-visible:ring-1 focus-visible:ring-luxury-gold/50 ${size} ${tone}`;

              return (
                <div
                  key={item.label}
                  className="relative"
                  onMouseEnter={() => {
                    if (item.items) setActiveDropdown(item.label);
                    onHoverChange?.(false);
                  }}
                  onMouseLeave={() => setActiveDropdown(null)}
                  onFocusCapture={() => item.items && setActiveDropdown(item.label)}
                  onBlurCapture={(event) => {
                    if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setActiveDropdown(null);
                  }}
                >
                  {item.href ? (
                    <Link href={item.href} className={shared}>{item.label}</Link>
                  ) : (
                    <button type="button" className={shared} aria-expanded={activeDropdown === item.label}>
                      {item.label}<ChevronIcon open={activeDropdown === item.label} />
                    </button>
                  )}

                  {item.items && activeDropdown === item.label && (
                    <DesktopDropdown
                      label={item.label}
                      items={item.items}
                      onClose={() => setActiveDropdown(null)}
                    />
                  )}
                </div>
              );
            })}
          </nav>

          <div className="flex items-center justify-end gap-1 justify-self-end lg:gap-3 xl:gap-4">
            <button
              type="button"
              onClick={() => setSearchPanelOpen((open) => !open)}
              className="flex min-h-10 flex-col items-center justify-center gap-0 px-1 text-luxury-light transition-colors hover:text-luxury-gold lg:min-h-[58px] xl:gap-1"
              aria-label={searchPanelOpen ? 'Zavřít vyhledávání' : 'Otevřít vyhledávání'}
            >
              <SearchIcon className="h-[22px] w-[22px] lg:h-7 lg:w-7" /><span className={actionLabel}>Hledat</span>
            </button>

            <Link href={isAuthenticated ? '/wishlist' : '/login'} className="relative flex min-h-10 flex-col items-center justify-center gap-0 px-1 text-luxury-light transition-colors hover:text-luxury-gold lg:min-h-[58px] xl:gap-1" aria-label="Oblíbené produkty">
              <HeartIcon /><span className={actionLabel}>Oblíbené</span>
            </Link>

            <Link href={isAuthenticated ? '/profile' : '/login'} className="flex min-h-10 flex-col items-center justify-center gap-0 px-1 text-luxury-light transition-colors hover:text-luxury-gold lg:min-h-[58px] xl:gap-1" aria-label={isAuthenticated ? 'Můj účet' : 'Přihlášení'}>
              <UserIcon /><span className={actionLabel}>{isAuthenticated ? user?.firstName || 'Účet' : 'Účet'}</span>
            </Link>

            <Link href="/cart" className="relative flex min-h-10 flex-col items-center justify-center gap-0 px-1 text-luxury-light transition-colors hover:text-luxury-gold lg:min-h-[58px] xl:gap-1" aria-label={`Košík, ${getTotalItems()} položek`}>
              <CartIcon /><span className={actionLabel}>Košík</span>
              {getTotalItems() > 0 && (
                <b className="absolute left-1/2 top-0 ml-1 grid h-[17px] min-w-[17px] place-items-center rounded-full bg-luxury-gold px-1 text-[9px] text-luxury-dark lg:top-1">
                  {getTotalItems()}
                </b>
              )}
            </Link>
          </div>
        </div>
      </header>

      {searchPanelOpen && (
        <div className="fixed left-0 right-0 top-[100px] z-40 border-b border-luxury-gold/20 bg-luxury-dark/98 p-3 shadow-xl backdrop-blur-xl lg:top-[114px]">
          <div className="relative mx-auto max-w-xl">
            <div className="flex h-11 items-center border-b border-luxury-gold/50">
              <input
                autoFocus
                type="search"
                value={search}
                onChange={(event) => setSearch(event.target.value)}
                placeholder="Hledat vůni…"
                className="min-w-0 flex-1 bg-transparent px-2 text-sm text-luxury-light outline-none placeholder:text-luxury-light/50"
                aria-label="Hledat produkt"
              />
              <SearchIcon />
            </div>
            <SearchDropdown searchTerm={search} isOpen={search.trim().length > 0} onClose={() => { setSearchPanelOpen(false); setSearch(''); }} />
          </div>
        </div>
      )}

      <MobileMenu isOpen={menuOpen} onClose={() => setMenuOpen(false)} />
    </>
  );
};

function DesktopDropdown({
  label,
  items,
  onClose,
}: {
  label: string;
  items: { label: string; href: string }[];
  onClose: () => void;
}) {
  const isBrands = label === 'Značky';
  const allBrandsLink = isBrands ? items[0] : null;
  const visibleItems = isBrands ? items.slice(1) : items;

  return (
    <div className="absolute left-1/2 top-full z-50 -translate-x-1/2 pt-4">
      <span className="absolute left-1/2 top-[11px] h-3 w-3 -translate-x-1/2 rotate-45 border-l border-t border-luxury-gold/35 bg-[#0b0b0b]" />
      <div
        className={`overflow-hidden rounded-2xl border border-luxury-gold/30 bg-[#0b0b0b] shadow-[0_28px_70px_rgba(0,0,0,0.72)] ${
          isBrands
            ? 'w-[720px] max-w-[calc(100vw-2rem)]'
            : 'w-[460px] max-w-[calc(100vw-2rem)]'
        }`}
      >
        {isBrands && allBrandsLink && (
          <div className="px-5 pb-3 pt-5">
            <Link
              href={allBrandsLink.href}
              onClick={onClose}
              className="group flex min-h-11 items-center justify-between rounded-xl bg-luxury-gold px-4 text-[12px] font-black uppercase tracking-[0.08em] text-luxury-dark transition-colors hover:bg-yellow-300"
            >
              {allBrandsLink.label}
              <DropdownArrow className="transition-transform duration-200 group-hover:translate-x-1" />
            </Link>
          </div>
        )}

        {visibleItems.length > 0 ? (
          <div className={`grid gap-1 overflow-y-auto px-4 pb-5 ${
            isBrands
              ? 'max-h-[min(55vh,430px)] grid-cols-3'
              : 'grid-cols-2 pt-4'
          }`}>
            {visibleItems.map((entry) => (
              <Link
                key={entry.href}
                href={entry.href}
                onClick={onClose}
                className="group flex min-h-11 items-center gap-2 rounded-lg px-3 py-2 text-left normal-case text-luxury-light/75 transition-all duration-200 hover:bg-luxury-gold/10 hover:text-luxury-gold"
              >
                <span className={`min-w-0 flex-1 text-[12px] font-semibold tracking-[0.025em] ${isBrands ? 'truncate' : 'whitespace-normal leading-snug'}`}>
                  {entry.label}
                </span>
                <DropdownArrow className="h-3.5 w-3.5 flex-none -translate-x-1 opacity-0 transition-all duration-200 group-hover:translate-x-0 group-hover:opacity-100" />
              </Link>
            ))}
          </div>
        ) : (
          <p className="px-6 pb-6 text-sm normal-case tracking-normal text-luxury-light/45">Načítání nabídky…</p>
        )}
      </div>
    </div>
  );
}

function DropdownArrow({ className = '' }: { className?: string }) {
  return (
    <svg className={`h-4 w-4 ${className}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="m9 5 7 7-7 7" />
    </svg>
  );
}

function MenuIcon() {
  return <svg className="h-[22px] w-[22px]" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.7} d="M4 6h16M4 12h16M4 18h16" /></svg>;
}

function SearchIcon({ className = 'h-[21px] w-[21px]' }: { className?: string }) {
  return <svg className={`${className} flex-none`} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.7} d="m21 21-4.35-4.35m1.35-5.65a7 7 0 1 1-14 0 7 7 0 0 1 14 0Z" /></svg>;
}

function HeartIcon() {
  return <svg className="h-[22px] w-[22px] lg:h-7 lg:w-7" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.7} d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 0 0 0-7.78Z" /></svg>;
}

function UserIcon() {
  return <svg className="h-[22px] w-[22px] lg:h-7 lg:w-7" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.7} d="M20 21a8 8 0 0 0-16 0m12-13a4 4 0 1 1-8 0 4 4 0 0 1 8 0Z" /></svg>;
}

function CartIcon() {
  return <svg className="h-[22px] w-[22px] lg:h-7 lg:w-7" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.7} d="M6 7h15l-1.5 9h-12L6 4H3m5 16h.01M18 20h.01" /></svg>;
}

function ChevronIcon({ open }: { open: boolean }) {
  return <svg className={`h-3 w-3 transition-transform ${open ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.7} d="m6 9 6 6 6-6" /></svg>;
}

export default StoreHeader;
