import { useState } from "react";
import { NavLink, useLocation } from "react-router-dom";
import { useFirstRun } from "../../firstRun/FirstRunContext";
import { useI18n } from "../../i18n/I18nContext";
import { firstRunNavKeys, isNavActive, navGroups, navGroupedItemsByKeys, navItemsByKeys } from "../../lib/nav";
import type { NavGroupKey, NavItem } from "../../lib/nav";
import { AppIcon } from "../ui/AppIcons";

export function SidebarNav() {
  const { pathname } = useLocation();
  const { t } = useI18n();
  const { active } = useFirstRun();
  const [openAdvanced, setOpenAdvanced] = useState<NavGroupKey | null>(null);
  const groups = active
    ? navGroupedItemsByKeys(firstRunNavKeys)
    : navGroups.map((group) => ({ group, items: navItemsByKeys(group.keys) }));

  function renderItem(item: NavItem) {
    const current = isNavActive(pathname, item);
    return (
      <NavLink
        key={item.key}
        to={item.path}
        className={`hb-nav__item${current ? " hb-nav__item--active" : ""}`}
      >
        <span className="hb-nav__ico" aria-hidden>
          <AppIcon name={item.key} size={18} />
        </span>
        <span>{t(item.labelKey)}</span>
      </NavLink>
    );
  }

  return (
    <aside className="hb-sidebar" aria-label={t("nav.navigate")}>
      <p className="hb-sidebar__label">{t("nav.navigate")}</p>
      {groups.map(({ group, items }) => {
        // 人在進階頁裡的時候要看得到自己在哪，不能還要先展開才知道。
        const insideGroup = items.some((item) => isNavActive(pathname, item));
        const expanded = !group.advanced || openAdvanced === group.key || insideGroup;
        return (
          <div className="hb-nav__group" key={group.key}>
            {group.advanced ? (
              <button
                type="button"
                className="hb-nav__group-toggle"
                aria-expanded={expanded}
                onClick={() => setOpenAdvanced(expanded ? null : group.key)}
              >
                {t(group.labelKey)}
              </button>
            ) : (
              <p className="hb-nav__group-label">{t(group.labelKey)}</p>
            )}
            {expanded ? <nav className="hb-nav">{items.map(renderItem)}</nav> : null}
          </div>
        );
      })}
    </aside>
  );
}
