import React, { useEffect, useState } from 'react';
import LanguageSwitcher from '../components/LanguageSwitcher';
import Icon from '../../shared/components/icon';
import { NavbarProps, NavItem } from '../navbar/types';
import { getTranslations } from '../../shared/utils/localization-util';

const Navbar: React.FC<NavbarProps> = ({
  currentPath,
  logo,
  onLogoClick,
  topLinks,
  items,
  language,
  languages,
  onLanguageChange,
  onSearch,
  member,
  onLogin,
  onLogout
}) => {
  const [menuOpen, setMenuOpen] = useState(false);
  const [query, setQuery] = useState('');
  const [activeMobileGroup, setActiveMobileGroup] = useState<string>();
  const translations = getTranslations(language.code ?? 'en-GB');
  const normalizePath = (path: string) => path.replace(/\/+$/, '');

  useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setMenuOpen(false);
        setActiveMobileGroup('');
      }
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, []);

  // Optional: when closing the burger menu, also close any open mobile dropdown group
  useEffect(() => {
    if (!menuOpen) setActiveMobileGroup('');
  }, [menuOpen]);

  const onSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const q = query.trim();
    if (!q) return;

    console.log('Search:', q);
    setMenuOpen(false);
    setActiveMobileGroup('');

    onSearch(q);
  };

  const toggleMobileGroup = (label: string) => {
    setActiveMobileGroup((current) => (current === label ? '' : label));
  };

  const isActive = (item: NavItem) => {
    return currentPath && normalizePath(currentPath) === normalizePath('/' + (item.href ?? ''));
  };

  const renderNavItem = (item: NavItem) => {
    const hasDropdown = item.items?.length || item.categories?.length;
    if (!hasDropdown) {
      return (
        <a key={item.label} href={item.href} className={`${isActive(item) ? 'nav__link nav__link--active' : 'nav__link'}`}>
          {item.label}
        </a>
      );
    }

    return (
      <div key={item.label} className={`nav__link-group ${item.items && (!item.categories || item.categories.length === 0) ? 'nav__link-group--small' : ''}`}>
        <a href={item.href} className="nav__link nav__link--has-dropdown">
          {item.label}
        </a>

        {item.categories && (!item.items || item.items.length === 0) && <CategorizedDropdown item={item} />}

        {item.items && (!item.categories || item.categories.length === 0) && (
          <div className="nav__dropdown nav__dropdown--small">
            {item.items.map((link) => (
              <div key={link.label} className="nav__dropdown__item" role="menuitem">
                <a href={link.href}>{link.label}</a>
              </div>
            ))}
          </div>
        )}
      </div>
    );
  };

  const CategorizedDropdown: React.FC<{ item: NavItem }> = ({ item }) => {
    const [activeIndex, setActiveIndex] = useState(0);

    if (!item.categories) return null;

    const activeCategory = item.categories[activeIndex];

    return (
      <div className="nav__dropdown">
        <div className="nav__dropdown__container">
          <div className="nav__dropdown__cols">
            <div className="nav__dropdown__toggles">
              {item.categories.map((cat, index) => (
                <button
                  key={cat.label}
                  type="button"
                  onMouseEnter={() => setActiveIndex(index)}
                  className={`nav__dropdown__toggle ${index === activeIndex ? 'nav__dropdown__toggle--active' : ''}`}>
                  {cat.label}
                  <Icon name="ui-chevron" width={16} height={16} />
                </button>
              ))}
            </div>

            <div className="nav__dropdown__col">
              <div className="nav__dropdown__col__items">
                {activeCategory.items.map((link) => (
                  <div key={link.label} className="nav__dropdown__item">
                    <a href={link.href}>{link.label}</a>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  };

  const renderMobileNavItem = (item: NavItem) => {
    const hasCategories = !!item.categories?.length;
    const hasItems = !!item.items?.length;
    const hasDropdown = hasCategories || hasItems;

    const isOpen = activeMobileGroup === item.label;

    if (!hasDropdown) {
      return (
        <a key={item.label} href={item.href} className={`nav__mobile-menu__link ${isActive(item) ? 'nav__mobile-menu__link--active' : ''}`}>
          {item.label}
        </a>
      );
    }

    return (
      <div
        key={item.label}
        className={`nav__link-group ${hasItems && !hasCategories ? 'nav__link-group--small' : ''} ${isOpen ? 'nav__link-group--active' : ''}`}>
        <a
          href={item.href}
          className={`nav__mobile-menu__link nav__link--has-dropdown ${isOpen ? 'nav__mobile-menu__link--active' : ''}`}
          aria-expanded={isOpen}
          onClick={(e) => {
            e.preventDefault();
            toggleMobileGroup(item.label);
          }}>
          {item.label}
        </a>

        {hasCategories && isOpen && (
          <div className="nav__dropdown">
            <div className="nav__dropdown__container">
              <div className="nav__dropdown__cols">
                <div className="nav__dropdown__toggles">
                  {item.categories!.map((category, index) => (
                    <button key={category.label} type="button" className={`nav__dropdown__toggle ${index === 0 ? 'nav__dropdown__toggle--active' : ''}`}>
                      {category.label}
                      <Icon name="ui-chevron" width={16} height={16} />
                    </button>
                  ))}
                </div>

                <div className="nav__dropdown__col">
                  <div className="nav__dropdown__col__items">
                    {item.categories![0].items.map((link) => (
                      <div key={link.label} className="nav__dropdown__item">
                        <a href={link.href}>{link.label}</a>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {hasItems && !hasCategories && isOpen && (
          <div className="nav__dropdown nav__dropdown--small" role="menu" aria-label={item.label}>
            {item.items!.map((link) => (
              <div key={link.label} className="nav__dropdown__item" role="menuitem">
                <a href={link.href}>{link.label}</a>
              </div>
            ))}
          </div>
        )}
      </div>
    );
  };

  const handleLogout = (event: React.MouseEvent<HTMLAnchorElement, MouseEvent>): void => {
    event.preventDefault();
    if (onLogout) {
      onLogout();
    }
  };

  const handleLogin = (event: React.MouseEvent<HTMLAnchorElement, MouseEvent>): void => {
    event.preventDefault();
    if (onLogin) {
      onLogin();
    }
  };

  return (
    <>
      <div className="nav__subnav">
        <div className="nav__subnav__container">
          <div className="nav__subnav__links">
            {member && (
              <span className="nav__subnav__member">
                {translations.LOGIN.WELCOME_X}
                {member.name}
              </span>
            )}
            {member ? (
              <>
                {onLogout && (
                  <a href="#" className="nav__subnav__link" onClick={handleLogout}>
                    {translations.LOGIN.LOGOUT}
                  </a>
                )}
              </>
            ) : (
              <>
                {onLogin && (
                  <a href="#" className="nav__subnav__link" onClick={handleLogin}>
                    {translations.LOGIN.LOGIN}
                  </a>
                )}
              </>
            )}
            <LanguageSwitcher
              value={language.code}
              languages={languages}
              onChange={(lang) => {
                console.log('Selected language:', lang);
                onLanguageChange(lang);
              }}
            />
            {topLinks.map((link, index) => (
              <a key={`topnav-${index}`} href={link.href} className="nav__subnav__link">
                {link.label}
              </a>
            ))}
          </div>
        </div>
      </div>
      <nav className="nav__primary">
        <div className="nav__container">
          <div className="nav__logo" onClick={onLogoClick}>
            {logo}
          </div>
          <div className="nav__wrapper">
            <div className="nav__links">{items && items.map(renderNavItem)}</div>
            <div className="nav__search">
              <form className="nav__search__form" role="search" aria-label="Site search" onSubmit={onSearchSubmit}>
                <div className={`nav__search__field ${query.trim().length ? 'nav__search__field--has-value' : ''}`}>
                  <input
                    id="nav-search"
                    className="nav__search__input"
                    type="search"
                    value={query}
                    onChange={(e) => setQuery(e.target.value)}
                    placeholder={translations.NAVBAR.SEARCH}
                    autoComplete="off"
                  />
                  <button type="button" className="nav__search__clear" aria-label="Clear search" onClick={() => setQuery('')}>
                    <Icon name="ui-close" width={12} height={12} />
                  </button>
                  <button className="nav__search__button" type="submit" aria-label="Search">
                    <Icon name="ui-search" width={16} height={16} />
                  </button>
                </div>
              </form>
            </div>
          </div>
          <button
            type="button"
            className={`nav__menu ${menuOpen ? 'nav__menu--opened' : ''}`}
            onClick={() => setMenuOpen((v) => !v)}
            aria-label="Main Menu"
            aria-expanded={menuOpen}
            aria-controls="nav-mobile-menu">
            <svg width="30" height="30" viewBox="0 0 100 100" aria-hidden="true">
              <path
                className="nav__menu__line nav__menu__line--1"
                d="M 20,29.000046 H 80.000231 C 80.000231,29.000046 94.498839,28.817352 94.532987,66.711331 94.543142,77.980673 90.966081,81.670246 85.259173,81.668997 79.552261,81.667751 75.000211,74.999942 75.000211,74.999942 L 25.000021,25.000058"
              />
              <path className="nav__menu__line nav__menu__line--2" d="M 20,50 H 80" />
              <path
                className="nav__menu__line nav__menu__line--3"
                d="M 20,70.999954 H 80.000231 C 80.000231,70.999954 94.498839,71.182648 94.532987,33.288669 94.543142,22.019327 90.966081,18.329754 85.259173,18.331003 79.552261,18.332249 75.000211,25.000058 75.000211,25.000058 L 25.000021,74.999942"
              />
            </svg>
          </button>
        </div>
        <div className={`nav__mobile-menu ${menuOpen ? 'nav__mobile-menu--active' : ''}`}>
          <div className="nav__mobile-menu__wrapper">
            <form className="nav__search__form nav__search__form--mobile" role="search" aria-label="Site search" onSubmit={onSearchSubmit}>
              <div className={`nav__search__field ${query.trim().length ? 'nav__search__field--has-value' : ''}`}>
                <input
                  className="nav__search__input"
                  type="search"
                  value={query}
                  onChange={(e) => setQuery(e.target.value)}
                  placeholder="Search…"
                  autoComplete="off"
                />
                <button type="button" className="nav__search__clear" aria-label="Clear search" onClick={() => setQuery('')}>
                  <Icon name="ui-close" width={12} height={12} />
                </button>
                <button className="nav__search__button" type="submit" aria-label="Search">
                  <Icon name="ui-search" width={16} height={16} />
                </button>
              </div>
            </form>
            {items && items.map(renderMobileNavItem)}
          </div>

          <div className="nav__subnav__links">
            <LanguageSwitcher
              value={language.code}
              languages={languages}
              onChange={(lang) => {
                console.log('Selected language:', lang);
                onLanguageChange(lang);
              }}
            />
            {topLinks.map((link, index) => (
              <a key={`topnav-${index}`} href={link.href} className="nav__subnav__link">
                {link.label}
              </a>
            ))}
          </div>
        </div>
      </nav>
    </>
  );
};

export default Navbar;
