import { useEffect, useState } from "react";
import { NavLink, useLocation } from "react-router-dom";
import { AppConfig } from "../api";
import {
  IconBook,
  IconCalendar,
  IconChevron,
  IconDisc,
  IconEmby,
  IconGrid,
  IconHeart,
  IconHome,
  IconImage,
  IconLayers,
  IconMusic,
  IconSettings,
  IconTrash,
  IconUser,
  IconWand,
} from "./icons";

interface NavItem {
  to: string;
  label: string;
  icon: JSX.Element;
}

const GROUPS: { id: string; label: string; icon: JSX.Element; links: NavItem[] }[] = [
  {
    id: "emby",
    label: "Emby",
    icon: <IconEmby />,
    links: [
      { to: "/emby/generator", label: "Thumb Studio", icon: <IconImage /> },
      { to: "/emby/avatar-generator", label: "Avatars", icon: <IconUser /> },
      { to: "/emby/collections", label: "Collection Covers", icon: <IconLayers /> },
      { to: "/emby/airing", label: "Airing Calendar", icon: <IconCalendar /> },
      { to: "/emby/bulk-assign", label: "Batch Artwork", icon: <IconGrid /> },
      { to: "/emby/favorites", label: "Favorites", icon: <IconHeart /> },
      { to: "/emby/homescreen", label: "Home Screen", icon: <IconLayers /> },
    ],
  },
  {
    id: "navidrome",
    label: "Navidrome",
    icon: <IconMusic />,
    links: [
      { to: "/navidrome/library", label: "Music Library", icon: <IconDisc /> },
      { to: "/navidrome/reporting", label: "Reporting", icon: <IconMusic /> },
      { to: "/navidrome/cleanup", label: "Library Cleanup", icon: <IconWand /> },
      { to: "/navidrome/metadata", label: "Metadata Editor", icon: <IconMusic /> },
      { to: "/collection-completeness", label: "Collection Completeness", icon: <IconLayers /> },
    ],
  },
  {
    id: "audiobookshelf",
    label: "Audiobookshelf",
    icon: <IconBook />,
    links: [{ to: "/audiobookshelf", label: "Overview", icon: <IconBook /> }],
  },
];

function Chip({ label, ok, configured }: { label: string; ok: boolean; configured: boolean }) {
  const cls = !configured ? "idle" : ok ? "" : "off";
  const text = !configured ? "Not configured" : ok ? "Connected" : "Offline";
  return (
    <div className="status-chip">
      <span className={`dot ${cls}`} />
      <span className="label">{label}</span>
      <span className="dim" style={{ fontSize: 11 }}>
        {text}
      </span>
    </div>
  );
}

interface Props {
  config: AppConfig | null;
  navidromeConnected: boolean;
  audiobookshelfConnected: boolean;
  mobileOpen: boolean;
  onClose: () => void;
}

export default function Sidebar({ config, navidromeConnected, audiobookshelfConnected, mobileOpen, onClose }: Props) {
  const location = useLocation();
  const activeGroup = GROUPS.find((g) => g.links.some((l) => location.pathname.startsWith(l.to)))?.id;

  // Accordion: only one category open at a time. The active route's group opens.
  const [open, setOpen] = useState<string | null>(activeGroup ?? null);

  useEffect(() => {
    if (activeGroup) setOpen(activeGroup);
  }, [activeGroup]);

  useEffect(() => {
    onClose();
  }, [location.pathname]); // eslint-disable-line react-hooks/exhaustive-deps

  const toggle = (id: string) => setOpen((cur) => (cur === id ? null : id));

  return (
    <>
      <button className={`nav-backdrop ${mobileOpen ? "open" : ""}`} onClick={onClose} aria-label="Close navigation" />
      <nav className={`nav ${mobileOpen ? "mobile-open" : ""}`}>
      <div className="nav-brand">
        <div className="nav-logo">H</div>
        <div className="nav-name">HomelabToolkit</div>
      </div>

      <div className="nav-scroll">
        <div className="nav-group">
          <NavLink to="/" end className={({ isActive }) => `nav-item nav-item-top ${isActive ? "active" : ""}`}>
            <IconHome />
            Dashboard
          </NavLink>
        </div>

        {GROUPS.map((g) => {
          const isOpen = open === g.id;
          return (
            <div className="nav-group" key={g.id}>
              <button className="nav-group-head" onClick={() => toggle(g.id)} aria-expanded={isOpen}>
                {g.icon}
                <span className="grow" style={{ textAlign: "left" }}>
                  {g.label}
                </span>
                <IconChevron className={`nav-caret ${isOpen ? "open" : ""}`} />
              </button>
              <div className={`nav-group-panel ${isOpen ? "open" : ""}`}>
                <div className="nav-group-inner">
                  {g.links.map((l) => (
                    <NavLink
                      key={l.to}
                      to={l.to}
                      className={({ isActive }) => `nav-item ${isActive ? "active" : ""}`}
                    >
                      {l.icon}
                      {l.label}
                    </NavLink>
                  ))}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <div className="nav-foot">
        <NavLink to="/tasks" className={({ isActive }) => `nav-item nav-item-top ${isActive ? "active" : ""}`}>
          <IconTrash />
          Tasks
        </NavLink>
        <NavLink to="/settings" className={({ isActive }) => `nav-item nav-item-top ${isActive ? "active" : ""}`}>
          <IconSettings />
          Settings
        </NavLink>
        <Chip label="Emby" ok={!!config?.emby.connected} configured={!!config?.emby.connected} />
        <Chip label="Navidrome" ok={navidromeConnected} configured={!!config?.navidrome.configured} />
        <Chip label="Audiobookshelf" ok={audiobookshelfConnected} configured={!!config?.audiobookshelf.configured} />
      </div>
      </nav>
    </>
  );
}
