import { useCallback, useEffect, useRef, useState } from 'react';
import { NavIcon } from '../../config/navIcons.jsx';
import './Sidebar.css';

function SectionChevron({ open }) {
  return (
    <svg
      className={`sidebar-chevron${open ? ' sidebar-chevron--open' : ''}`}
      width="14"
      height="14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      aria-hidden
    >
      <path d="M6 9l6 6 6-6" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function LogoutIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
      <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function groupIsOpen(key, item, openGroups) {
  if (openGroups[key] !== undefined) return openGroups[key];
  return item.defaultOpen ?? false;
}

function renderNavLabel(item) {
  return (
    <>
      <NavIcon name={item.icon || item.key} />
      <span className="sidebar-nav-label">{item.label}</span>
    </>
  );
}

function Sidebar({ activePage, navItems = [], onChangePage, onLogout, onToggleSidebar, onSidebarMouseLeave }) {
  const [openGroups, setOpenGroups] = useState({});
  const prevPageRef = useRef(null);

  const toggleGroup = useCallback((key, item) => {
    setOpenGroups((prev) => ({
      ...prev,
      [key]: !groupIsOpen(key, item, prev)
    }));
  }, []);

  useEffect(() => {
    const prev = prevPageRef.current;
    prevPageRef.current = activePage;

    setOpenGroups((prevOpen) => {
      const next = { ...prevOpen };
      let changed = false;
      for (const item of navItems) {
        if (item.type !== 'group' || !item.items?.length) continue;
        const wasIn = prev != null && item.items.some((sub) => sub.key === prev);
        const isIn = item.items.some((sub) => sub.key === activePage);
        if (!wasIn && isIn && next[item.key] !== true) {
          next[item.key] = true;
          changed = true;
        }
      }
      return changed ? next : prevOpen;
    });
  }, [activePage, navItems]);

  return (
    <aside className="app-sidebar" onMouseLeave={onSidebarMouseLeave}>
      <div className="sidebar-logo">
        <h3 className="sidebar-logo-text">Navigation</h3>
        {onToggleSidebar && (
          <button
            type="button"
            className="sidebar-close-button"
            onClick={onToggleSidebar}
            aria-label="Close navigation"
          >
            <svg className="sidebar-close-button-icon" width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
              <path
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M15 18l-6-6 6-6"
              />
            </svg>
          </button>
        )}
      </div>

      <nav className="sidebar-nav" aria-label="Main">
        <ul className="sidebar-menu">
          {navItems.map((item) => {
            if (item.type === 'group' && item.items?.length) {
              const open = groupIsOpen(item.key, item, openGroups);
              const hasActiveChild = item.items.some((sub) => sub.key === activePage);

              return (
                <li
                  key={item.key}
                  className={`sidebar-nav-group${open ? ' is-open' : ''}${hasActiveChild ? ' is-active-section' : ''}`}
                >
                  <button
                    type="button"
                    className="sidebar-menu-link"
                    aria-expanded={open}
                    onClick={() => toggleGroup(item.key, item)}
                  >
                    <span className="sidebar-menu-link__main">
                      {renderNavLabel(item)}
                    </span>
                    <SectionChevron open={open} />
                  </button>
                  <ul className="sidebar-submenu">
                    {item.items.map((sub) => (
                      <li key={sub.key} className={activePage === sub.key ? 'is-active' : ''}>
                        <button
                          type="button"
                          className={`sidebar-submenu-link${activePage === sub.key ? ' is-active' : ''}`}
                          onClick={() => onChangePage(sub.key)}
                        >
                          {renderNavLabel(sub)}
                        </button>
                      </li>
                    ))}
                  </ul>
                </li>
              );
            }

            if (item.type === 'heading') {
              return (
                <li key={item.key} className="sidebar-nav-heading" role="presentation">
                  {item.label}
                </li>
              );
            }

            return (
              <li key={item.key}>
                <button
                  type="button"
                  className={`sidebar-menu-link sidebar-menu-link--flat${activePage === item.key ? ' is-active' : ''}`}
                  onClick={() => onChangePage(item.key)}
                >
                  {renderNavLabel(item)}
                </button>
              </li>
            );
          })}
        </ul>

        <div className="sidebar-nav-footer">
          <button className="sidebar-logout-button" type="button" onClick={onLogout}>
            <LogoutIcon />
            <span className="sidebar-nav-label">Logout</span>
          </button>
        </div>
      </nav>
    </aside>
  );
}

export default Sidebar;
