import React, { useCallback, useEffect, useMemo, useState } from "react";
import { ADMIN_NAV_SECTIONS } from "../../config/adminNav.jsx";

const STORAGE_KEY = "ptw-portal-sidebar-sections";

function SectionChevron({ open }) {
  return (
    <svg
      className={`portal-sidebar__chevron${open ? " portal-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 readStoredSections(sectionIds) {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== "object") return null;
    const next = {};
    for (const id of sectionIds) {
      if (typeof parsed[id] === "boolean") {
        next[id] = parsed[id];
      }
    }
    if (!Object.keys(next).length) return null;
    // Older builds defaulted every section to open; start collapsed on entry instead.
    if (sectionIds.length > 0 && sectionIds.every((id) => next[id] === true)) {
      return null;
    }
    return next;
  } catch {
    return null;
  }
}

function defaultOpenSections(sectionIds) {
  return Object.fromEntries(sectionIds.map((id) => [id, false]));
}

const PortalSidebar = ({
  collapsed,
  activeNav,
  onNavigate,
  navSections = ADMIN_NAV_SECTIONS,
  onLogout,
}) => {
  const sectionIds = useMemo(
    () => navSections.map((section) => section.id),
    [navSections]
  );

  const activeSectionId = useMemo(() => {
    for (const section of navSections) {
      if (section.items.some((item) => !item.external && item.id === activeNav)) {
        return section.id;
      }
    }
    return null;
  }, [navSections, activeNav]);

  const [openSections, setOpenSections] = useState(() => {
    const stored = readStoredSections(sectionIds);
    return stored ?? defaultOpenSections(sectionIds);
  });

  useEffect(() => {
    setOpenSections((prev) => {
      const stored = readStoredSections(sectionIds);
      if (stored) return stored;
      const next = { ...prev };
      for (const id of sectionIds) {
        if (next[id] === undefined) next[id] = false;
      }
      return next;
    });
  }, [sectionIds]);

  useEffect(() => {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(openSections));
    } catch {
      /* ignore */
    }
  }, [openSections]);

  const toggleSection = useCallback((sectionId) => {
    setOpenSections((prev) => ({
      ...prev,
      [sectionId]: !prev[sectionId],
    }));
  }, []);

  const handleItemClick = (item) => {
    if (item.external && item.onNavigate) {
      item.onNavigate();
      return;
    }
    onNavigate(item.id);
  };

  const renderCollapsedItem = (item) => {
    const Icon = item.icon;
    const active = !item.external && activeNav === item.id;
    return (
      <li key={item.id}>
        <button
          type="button"
          className={`portal-sidebar__icon-link${active ? " is-active" : ""}`}
          onClick={() => handleItemClick(item)}
          title={item.label}
        >
          <span className="portal-sidebar__menu-icon">{Icon ? <Icon /> : null}</span>
        </button>
      </li>
    );
  };

  const renderSubmenuItem = (item) => {
    const Icon = item.icon;
    const active = !item.external && activeNav === item.id;
    return (
      <li key={item.id} className={active ? "is-active" : ""}>
        <button
          type="button"
          className={`portal-sidebar__submenu-link${active ? " is-active" : ""}${item.external ? " is-external" : ""}`}
          onClick={() => handleItemClick(item)}
        >
          <span className="portal-sidebar__menu-icon">{Icon ? <Icon /> : null}</span>
          <span className="portal-sidebar__menu-text">{item.label}</span>
        </button>
      </li>
    );
  };

  return (
    <aside
      className={`portal-sidebar${collapsed ? " portal-sidebar--collapsed" : ""}`}
      aria-label="Main navigation"
    >
      {!collapsed ? (
        <div className="portal-sidebar__header">
          <h3>Navigation</h3>
        </div>
      ) : null}

      <div className="portal-sidebar__scroll">
        {collapsed ? (
          <ul className="portal-sidebar__menu portal-sidebar__menu--collapsed">
            {navSections.flatMap((section) => section.items.map(renderCollapsedItem))}
          </ul>
        ) : (
          <ul className="portal-sidebar__menu">
            {navSections.map((section) => {
              const open = openSections[section.id] === true;
              const isActiveSection = activeSectionId === section.id;

              return (
                <li
                  key={section.id}
                  className={`portal-sidebar__dropdown${open ? " is-open" : ""}${isActiveSection ? " is-active-section" : ""}`}
                >
                  <button
                    type="button"
                    className="portal-sidebar__menu-link"
                    aria-expanded={open}
                    onClick={() => toggleSection(section.id)}
                  >
                    <span className="portal-sidebar__menu-text">{section.title}</span>
                    <SectionChevron open={open} />
                  </button>
                  <ul className="portal-sidebar__submenu">
                    {section.items.map(renderSubmenuItem)}
                  </ul>
                </li>
              );
            })}
          </ul>
        )}
      </div>

      <div className="portal-sidebar__footer">
        <button
          type="button"
          className="portal-logout"
          onClick={() => (onLogout ? onLogout() : window.alert("Signed out."))}
          title="Logout"
        >
          <LogoutIcon />
          {!collapsed ? <span>Logout</span> : null}
        </button>
      </div>
    </aside>
  );
};

export default PortalSidebar;
