import { useEffect, useMemo, useState } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import './NavigationTabs.css';

const NavigationTabs = ({
  isAdmin,
  onProtectedNavigate,
  profileName,
  onLogout,
  onRefresh,
  onToggleNotifications,
  notificationPanelOpen,
  notificationLoading
}) => {
  const location = useLocation();
  const navigate = useNavigate();
  const [mobileOpen, setMobileOpen] = useState(false);

  const tabs = useMemo(() => {
    const items = [{ to: '/', label: 'Slots buchen' }];
    if (isAdmin) {
      items.push({ to: '/store-watch', label: 'Betriebs-Monitoring' });
      items.push({ to: '/journal', label: 'Abhol-Journal' });
      items.push({ to: '/debug', label: 'Debug' });
      items.push({ to: '/admin', label: 'Admin' });
    }
    return items;
  }, [isAdmin]);
  const hasNavigation = tabs.length > 1;

  const handleClick = (event, to) => {
    event.preventDefault();
    if (to === location.pathname) {
      return;
    }
    const label = tabs.find((tab) => tab.to === to)?.label || '';
    const proceed = () => navigate(to);
    if (onProtectedNavigate) {
      onProtectedNavigate(`zur Seite "${label}" zu wechseln`, proceed);
      return;
    }
    proceed();
  };

  useEffect(() => {
    setMobileOpen(false);
  }, [location.pathname]);

  const handleToolAction = (action) => {
    setMobileOpen(false);
    action?.();
  };

  const renderLink = (tab, className) => {
    const isActive = location.pathname === tab.to;
    return (
      <Link
        key={tab.to}
        to={tab.to}
        onClick={(event) => handleClick(event, tab.to)}
        className={`${className}${isActive ? ' is-active' : ''}`}
        aria-current={isActive ? 'page' : undefined}
      >
        {tab.label}
      </Link>
    );
  };

  return (
    <nav className={`app-navigation ${hasNavigation ? '' : 'app-navigation--compact'}`} aria-label="Navigation">
      <div className="app-navigation__mobile-header">
        <img className="app-navigation__brand-mark" src="/branding/logo-mark.png" alt="" aria-hidden="true" />
        <span className="app-navigation__product-name">Foodsharing Manager</span>
        <button
          type="button"
          className="app-navigation__menu-toggle"
          aria-label={mobileOpen ? 'Menü schließen' : 'Menü öffnen'}
          aria-expanded={mobileOpen}
          aria-controls="mobile-navigation"
          onClick={() => setMobileOpen((open) => !open)}
        >
          <svg viewBox="0 0 24 24" stroke="currentColor" fill="none" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            {mobileOpen ? (
              <>
                <line x1="18" y1="6" x2="6" y2="18" />
                <line x1="6" y1="6" x2="18" y2="18" />
              </>
            ) : (
              <>
                <line x1="3" y1="6" x2="21" y2="6" />
                <line x1="3" y1="12" x2="21" y2="12" />
                <line x1="3" y1="18" x2="21" y2="18" />
              </>
            )}
          </svg>
        </button>
      </div>

      {mobileOpen && (
        <div id="mobile-navigation" className="app-navigation__mobile-menu">
          {hasNavigation && (
            <div className="app-navigation__mobile-links">
              {tabs.map((tab) => renderLink(tab, 'app-navigation__mobile-link'))}
            </div>
          )}
          {location.pathname === '/' && (onRefresh || onToggleNotifications) && (
            <div className="app-navigation__tools">
              <span>Werkzeuge</span>
              {onRefresh && (
                <button type="button" className="app-navigation__tool" onClick={() => handleToolAction(onRefresh)}>
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <path d="M20 11a8.1 8.1 0 0 0-15.5-2M4 5v4h4" />
                    <path d="M4 13a8.1 8.1 0 0 0 15.5 2M20 19v-4h-4" />
                  </svg>
                  Betriebe aktualisieren
                </button>
              )}
              {onToggleNotifications && (
                <button
                  type="button"
                  className={`app-navigation__tool ${notificationPanelOpen ? 'is-active' : ''}`}
                  onClick={() => handleToolAction(onToggleNotifications)}
                >
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543-.89 3.31.877 2.42 2.42a1.724 1.724 0 0 0 1.065 2.572c1.757.426 1.757 2.924 0 3.35a1.724 1.724 0 0 0-1.066 2.573c.89 1.543-.877 3.31-2.42 2.42a1.724 1.724 0 0 0-2.572 1.065c-.426 1.757-2.924 1.757-3.35 0a1.724 1.724 0 0 0-2.573-1.066c-1.543.89-3.31-.877-2.42-2.42a1.724 1.724 0 0 0-1.065-2.572c-1.757-.426-1.757-2.924 0-3.35a1.724 1.724 0 0 0 1.066-2.573c-.89-1.543.877-3.31 2.42-2.42.996.575 2.273.155 2.573-1.065z" />
                    <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z" />
                  </svg>
                  Benachrichtigungen
                </button>
              )}
              {notificationLoading && <small>Lade...</small>}
            </div>
          )}
          <div className="app-navigation__account">
            <div>
              <span>Angemeldet</span>
              <strong>{profileName || 'Profil'}</strong>
            </div>
            <button type="button" onClick={onLogout}>Logout</button>
          </div>
        </div>
      )}

      {hasNavigation && (
        <div className="app-navigation__desktop">
          <Link to="/" className="app-navigation__brand" aria-label="Foodsharing Manager Startseite">
            <img className="app-navigation__brand-mark" src="/branding/logo-mark.png" alt="" aria-hidden="true" />
            <span>Foodsharing Manager</span>
          </Link>
          {tabs.map((tab) => renderLink(tab, 'app-navigation__desktop-link'))}
        </div>
      )}
    </nav>
  );
};

export default NavigationTabs;
