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

interface MenuItem {
  label: string;
  href?: string;
  hasDropdown?: boolean;
  dropdownItems?: { label: string; href: string }[];
}

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

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

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

const TopNavbar: React.FC<TopNavbarProps> = ({ onHoverChange }) => {
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [isScrolled, setIsScrolled] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [isSearchOpen, setIsSearchOpen] = useState(false);
  const [isMobileSearchOpen, setIsMobileSearchOpen] = useState(false);
  const [mobileSearchTerm, setMobileSearchTerm] = useState('');
  const [hoveredItem, setHoveredItem] = useState<string | null>(null);
  const [activeDropdown, setActiveDropdown] = useState<string | null>(null);
  const [brands, setBrands] = useState<Brand[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const { getTotalItems } = useCart();
  const { isAuthenticated, user } = useAuth();
  const mobileSearchRef = useRef<HTMLDivElement>(null);

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

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

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (mobileSearchRef.current && !mobileSearchRef.current.contains(event.target as Node)) {
        setIsMobileSearchOpen(false);
      }
    };

    if (isMobileSearchOpen) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => document.removeEventListener('mousedown', handleClickOutside);
    }
  }, [isMobileSearchOpen]);

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

    fetchData();
  }, []);

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

  const handleItemEnter = (itemLabel: string) => {
    setHoveredItem(itemLabel);
    const item = menuItems.find(m => m.label === itemLabel);
    if (item?.hasDropdown) {
      setActiveDropdown(itemLabel);
      onHoverChange?.(false);
    }
  };

  return (
    <>
      {/* Row 1: Logo, Search, Actions */}
      <nav
        className="fixed top-10 xs:top-11 sm:top-12 left-0 right-0 z-50 transition-all duration-300"
        style={{
          backgroundColor: isScrolled ? 'rgba(10, 10, 10, 0.95)' : 'rgba(10, 10, 10, 0.77)',
        }}
      >
        <div className="max-w-7xl mx-auto px-1.5 xs:px-2 sm:px-4 md:px-6 lg:px-8 w-full">
          <div className="flex items-center justify-between h-14 xs:h-16 sm:h-20 lg:h-20 gap-1 xs:gap-2 sm:gap-3 lg:gap-4">
            {/* Logo and Brand */}
            <Link href="/">
              <div className="flex items-center gap-1.5 xs:gap-2 sm:gap-3 md:gap-4 flex-shrink-0 cursor-pointer transition-all duration-300 transform hover:scale-110 active:scale-105" style={{transformOrigin: 'center'}}>
                <img
                  src="/images/logo.png"
                  alt="VYSTŘÍKEJ TO"
                  className="h-8 xs:h-9 sm:h-12 w-auto"
                />
                <div className="flex flex-col">
                  <h2 className="text-xs sm:text-xl lg:text-2xl xl:text-3xl font-aptos font-black text-luxury-gold leading-tight">
                    VYSTŘÍKEJ TO
                  </h2>
                  <p className="text-[10px] sm:text-xs lg:text-sm font-medium text-luxury-light leading-tight">
                    Celé parfémy
                  </p>
                </div>
              </div>
            </Link>

            {/* Search Bar - Hidden on mobile/tablet, shown on desktop */}
            <div className="hidden lg:flex flex-1 max-w-md lg:max-w-lg">
              <div className="relative w-full">
                <svg
                  className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-luxury-gold pointer-events-none"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                  />
                </svg>
                <input
                  type="text"
                  placeholder="Hledat produkty..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  onFocus={() => setIsSearchOpen(true)}
                  onBlur={() => setTimeout(() => setIsSearchOpen(false), 200)}
                  className="w-full pl-10 pr-4 py-2.5 bg-luxury-dark/50 text-luxury-light rounded-lg border-2 border-luxury-gold/50 focus:outline-none focus:ring-2 focus:ring-luxury-gold focus:border-luxury-gold transition-all placeholder:text-luxury-gold/60 shadow-sm hover:border-luxury-gold/70"
                />
                <SearchDropdown
                  searchTerm={searchTerm}
                  isOpen={isSearchOpen && searchTerm.trim().length > 0}
                  onClose={() => {
                    setIsSearchOpen(false);
                    setSearchTerm('');
                  }}
                />
              </div>
            </div>

            {/* Right Navigation */}
            <div className="flex items-center justify-end gap-1 xs:gap-2 sm:gap-3 lg:gap-4 xl:gap-8 flex-shrink-0">
              {/* Mobile Search Icon */}
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  setIsMobileSearchOpen(!isMobileSearchOpen);
                }}
                className="lg:hidden w-11 h-11 text-luxury-gold hover:text-yellow-300 transition-colors flex flex-col items-center justify-center"
                aria-label="Otevřít vyhledávání"
              >
                <svg
                  className="w-4 xs:w-5 sm:w-5 h-4 xs:h-5 sm:h-5"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                  />
                </svg>
              </button>

              <Link href={isAuthenticated ? "/wishlist" : "/login"} className="hidden lg:block">
                <button className="w-11 h-11 sm:w-auto sm:h-auto text-red-500 hover:text-red-400 transition-colors flex flex-col items-center justify-center gap-0 xs:gap-0.5 sm:gap-1 sm:py-0.5 sm:p-0.5" aria-label="Oblíbené produkty">
                  <svg
                    className="w-4 xs:w-5 sm:w-5 h-4 xs:h-5 sm:h-5 lg:w-6 lg:h-6"
                    fill="currentColor"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
                    />
                  </svg>
                  <span className="hidden xl:block text-sm lg:text-base font-bold font-aptos text-red-500">Oblíbené</span>
                </button>
              </Link>

              <Link href={isAuthenticated ? "/profile" : "/login"} className="hidden lg:block">
                <button className="w-11 h-11 sm:w-auto sm:h-auto text-luxury-gold hover:text-yellow-300 transition-colors flex flex-col items-center justify-center gap-0 xs:gap-0.5 sm:gap-1 sm:py-0.5 sm:p-0.5" aria-label={isAuthenticated ? 'Uživatelský profil' : 'Přihlášení'}>
                  <svg
                    className="w-4 xs:w-5 sm:w-5 h-4 xs:h-5 sm:h-5 lg:w-6 lg:h-6"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
                    />
                  </svg>
                  <span className="hidden xl:block text-sm lg:text-base font-bold font-aptos text-luxury-gold">
                    {isAuthenticated ? `${user?.firstName}` : 'Klientská zóna'}
                  </span>
                </button>
              </Link>

              <Link href="/cart">
                <button className="w-11 h-11 sm:w-auto sm:h-auto text-luxury-light hover:text-white transition-colors flex flex-col items-center justify-center gap-0 xs:gap-0.5 sm:gap-1 relative sm:py-0.5 sm:p-0.5" aria-label="Košík">
                  <svg
                    className="w-4 xs:w-5 sm:w-5 h-4 xs:h-5 sm:h-5 lg:w-6 lg:h-6"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"
                    />
                  </svg>
                  <span className="hidden xl:block text-sm lg:text-base font-bold font-aptos text-luxury-light">Košík</span>
                  {getTotalItems() > 0 && (
                    <span className="absolute -top-0.5 -right-0.5 xs:-top-1 xs:-right-1 sm:-top-2 sm:-right-2 bg-red-500 text-white text-[8px] xs:text-[10px] sm:text-xs rounded-full w-3.5 h-3.5 xs:w-4 xs:h-4 sm:w-5 sm:h-5 flex items-center justify-center font-bold leading-none">
                      {getTotalItems()}
                    </span>
                  )}
                </button>
              </Link>
            </div>

            <button
              onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
              className="lg:hidden w-11 h-11 text-luxury-gold hover:text-yellow-300 transition-colors flex-shrink-0 flex items-center justify-center"
              aria-label={isMobileMenuOpen ? 'Zavřít menu' : 'Otevřít menu'}
              aria-expanded={isMobileMenuOpen}
            >
              <svg
                className="w-6 h-6"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                {isMobileMenuOpen ? (
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                ) : (
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                )}
              </svg>
            </button>
          </div>
        </div>
      </nav>

      {/* Mobile Search Bar */}
      {isMobileSearchOpen && (
        <div ref={mobileSearchRef} className="fixed top-24 xs:top-[6.75rem] sm:top-32 left-0 right-0 lg:hidden bg-luxury-dark border-b-2 border-luxury-gold/30 p-3 z-40 shadow-lg">
          <div className="max-w-7xl mx-auto px-2 sm:px-4">
            <div className="relative">
              <svg
                className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-luxury-gold pointer-events-none"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                />
              </svg>
              <input
                type="text"
                placeholder="Hledat produkty..."
                value={mobileSearchTerm}
                onChange={(e) => setMobileSearchTerm(e.target.value)}
                onFocus={() => setIsMobileSearchOpen(true)}
                className="w-full pl-10 pr-4 py-2.5 bg-luxury-dark/50 text-luxury-light rounded-lg border-2 border-luxury-gold/50 focus:outline-none focus:ring-2 focus:ring-luxury-gold focus:border-luxury-gold transition-all placeholder:text-luxury-gold/60 shadow-sm hover:border-luxury-gold/70"
              />
              <SearchDropdown
                searchTerm={mobileSearchTerm}
                isOpen={isMobileSearchOpen && mobileSearchTerm.trim().length > 0}
                onClose={() => {
                  setIsMobileSearchOpen(false);
                  setMobileSearchTerm('');
                }}
              />
            </div>
          </div>
        </div>
      )}

      <MobileMenu
        isOpen={isMobileMenuOpen}
        onClose={() => setIsMobileMenuOpen(false)}
      />

      {/* Row 2: Menu Items */}
      <nav
        className="hidden lg:block fixed left-0 right-0 z-40 transition-all duration-300 lg:top-32"
        style={{
          backgroundColor: isScrolled ? 'rgba(10, 10, 10, 0.95)' : 'rgba(10, 10, 10, 0.77)',
        }}
      >
        <div className="w-full">
            <div className="flex items-center justify-center h-12 gap-1 md:gap-2 px-2 overflow-visible">
            {menuItems.map((item, index) => (
              <div
                key={index}
                className="relative flex items-center flex-shrink-0 group"
                onMouseEnter={() => handleItemEnter(item.label)}
                onMouseLeave={() => {
                  setHoveredItem(null);
                  setActiveDropdown(null);
                  onHoverChange?.(false);
                }}
              >
                {/* Menu Button or Link */}
                {item.href && !item.hasDropdown ? (
                  <Link
                    href={item.href}
                    className={`transition-all px-2 sm:px-3 md:px-4 lg:px-5 py-2 md:py-3 text-xs sm:text-sm md:text-base lg:text-lg font-semibold font-aptos whitespace-nowrap uppercase flex items-center gap-1.5 relative ${
                      item.label === 'Výprodej'
                        ? 'border-b-2'
                        : item.label === 'Výhodné sady' || item.label === 'Dárkové poukazy'
                        ? 'border-b-2'
                        : 'text-luxury-light hover:text-luxury-gold'
                    }`}
                    style={
                      item.label === 'Výprodej'
                        ? {
                            color: hoveredItem === item.label ? '#ef4444' : '#dc2626',
                            borderBottomColor: hoveredItem === item.label ? '#ef4444' : '#dc2626',
                            transform: hoveredItem === item.label ? 'scale(1.08)' : 'scale(1)',
                            paddingBottom: '0.25rem',
                          }
                        : item.label === 'Výhodné sady' || item.label === 'Dárkové poukazy'
                        ? {
                            color: hoveredItem === item.label ? '#fcd34d' : '#f3bd35',
                            borderBottomColor: hoveredItem === item.label ? '#fcd34d' : '#f3bd35',
                            transform: hoveredItem === item.label ? 'scale(1.08)' : 'scale(1)',
                            paddingBottom: '0.25rem',
                          }
                        : {
                            color: hoveredItem === item.label ? '#f3bd35' : '#f5f5f5',
                            transform: hoveredItem === item.label ? 'scale(1.08)' : 'scale(1)',
                          }
                    }
                  >
                    {item.label}
                  </Link>
                ) : (
                  <button
                    className={`transition-all px-2 sm:px-3 md:px-4 lg:px-5 py-2 md:py-3 text-xs sm:text-sm md:text-base lg:text-lg font-semibold font-aptos whitespace-nowrap uppercase flex items-center gap-1.5 relative ${
                      item.label === 'Výprodej'
                        ? 'border-b-2'
                        : item.label === 'Výhodné sady' || item.label === 'Dárkové poukazy'
                        ? 'border-b-2'
                        : 'text-luxury-light hover:text-luxury-gold'
                    }`}
                    style={
                      item.label === 'Výprodej'
                        ? {
                            color: hoveredItem === item.label ? '#ef4444' : '#dc2626',
                            borderBottomColor: hoveredItem === item.label ? '#ef4444' : '#dc2626',
                            transform: hoveredItem === item.label ? 'scale(1.08)' : 'scale(1)',
                            paddingBottom: '0.25rem',
                          }
                        : item.label === 'Výhodné sady' || item.label === 'Dárkové poukazy'
                        ? {
                            color: hoveredItem === item.label ? '#fcd34d' : '#f3bd35',
                            borderBottomColor: hoveredItem === item.label ? '#fcd34d' : '#f3bd35',
                            transform: hoveredItem === item.label ? 'scale(1.08)' : 'scale(1)',
                            paddingBottom: '0.25rem',
                          }
                        : {
                            color: hoveredItem === item.label ? '#f3bd35' : '#f5f5f5',
                            transform: hoveredItem === item.label ? 'scale(1.08)' : 'scale(1)',
                          }
                    }
                  >
                    {item.label}
                    {item.hasDropdown && (
                      <svg
                        className={`w-3 h-3 sm:w-4 sm:h-4 transition-transform duration-300 ${
                          activeDropdown === item.label ? 'rotate-180' : ''
                        }`}
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M19 14l-7 7m0 0l-7-7m7 7V3"
                        />
                      </svg>
                    )}
                  </button>
                )}

                {/* Dropdown Menu */}
                {item.hasDropdown && activeDropdown === item.label && (
                  <div
                    className="absolute top-full left-1/2 -translate-x-1/2 mt-0 pt-2 z-50 animate-in fade-in duration-200 pointer-events-auto"
                  >
                    <div className={`bg-gradient-to-b from-luxury-dark to-luxury-dark/95 border border-luxury-gold/40 rounded-md shadow-2xl w-max min-w-[200px] backdrop-blur-md ${
                      item.label === 'Značky' ? 'overflow-y-auto max-h-96' : 'overflow-hidden'
                    }`}
                    style={{
                      boxShadow: '0 8px 32px rgba(221, 162, 13, 0.15), 0 0 20px rgba(221, 162, 13, 0.1)'
                    }}>
                      {/* Dropdown Header - Hidden for Celé parfémy and Značky */}
                      {item.label !== 'Značky' && item.label !== 'Celé parfémy' && (
                        <div className="px-4 sm:px-5 md:px-6 py-3 md:py-4 border-b border-luxury-gold/20 bg-gradient-to-r from-luxury-gold/5 to-transparent sticky top-0">
                          <p className="text-luxury-gold text-xs font-black uppercase tracking-widest">
                            {item.label}
                          </p>
                        </div>
                      )}

                      {/* Dropdown Items */}
                      {item.dropdownItems && item.dropdownItems.length > 0 ? (
                        item.dropdownItems.map((dropdownItem, dropdownIndex) => (
                          <Link
                            key={dropdownIndex}
                            href={dropdownItem.href}
                            className="block px-4 sm:px-5 md:px-6 py-3 md:py-4 text-xs sm:text-sm md:text-sm text-luxury-light/90 hover:text-luxury-gold transition-all duration-200 border-b border-luxury-gold/10 last:border-b-0 font-aptos uppercase relative group hover:bg-gradient-to-r hover:from-luxury-gold/8 hover:to-transparent"
                          >
                            <span className="absolute left-3 opacity-0 group-hover:opacity-100 transition-all duration-200 text-luxury-gold font-bold">›</span>
                            <span className="group-hover:pl-2 transition-all duration-200 inline-block">{dropdownItem.label}</span>
                          </Link>
                        ))
                      ) : (
                        <div className="px-4 sm:px-5 md:px-6 py-3 md:py-4 text-xs text-luxury-light/50 font-aptos">
                          Načítání...
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {index < menuItems.length - 1 && (
                  <span className="text-luxury-gold/50 ml-1 md:ml-2 hidden sm:inline">|</span>
                )}
              </div>
            ))}
          </div>
        </div>
      </nav>
    </>
  );
};

export default TopNavbar;
