import { useEffect, useState } from "react";
import { Navigate, Route, Routes, useLocation } from "react-router-dom";
import Sidebar from "./components/Sidebar";
import CommandPalette from "./components/CommandPalette";
import { AppConfig, apiGet } from "./api";
import { IconClose, IconMenu } from "./components/icons";
import Dashboard from "./pages/Dashboard";
import Generator from "./pages/emby/Generator";
import AvatarGenerator from "./pages/emby/AvatarGenerator";
import Collections from "./pages/emby/Collections";
import Airing from "./pages/emby/Airing";
import BulkAssign from "./pages/emby/BulkAssign";
import Favorites from "./pages/emby/Favorites";
import HomescreenEditor from "./pages/emby/HomescreenEditor";
import Library from "./pages/navidrome/Library";
import Reporting from "./pages/navidrome/Reporting";
import CoverManager from "./pages/navidrome/CoverManager";
import Metadata from "./pages/navidrome/Metadata";
import CollectionCompleteness from "./pages/navidrome/CollectionCompleteness";
import Settings from "./pages/Settings";
import AudiobookshelfOverview from "./pages/audiobookshelf/Overview";
import Tasks from "./pages/Tasks";

const CRUMBS: Record<string, [string, string]> = {
  "/": ["", "Dashboard"],
  "/emby/generator": ["Emby", "Thumb Studio"],
  "/emby/avatar-generator": ["Emby", "Avatars"],
  "/emby/collections": ["Emby", "Collection Covers"],
  "/emby/airing": ["Emby", "Airing Calendar"],
  "/emby/bulk-assign": ["Emby", "Batch Artwork"],
  "/emby/favorites": ["Emby", "Favorites"],
  "/emby/homescreen": ["Emby", "Home Screen"],
  "/navidrome/library": ["Navidrome", "Music Library"],
  "/navidrome/reporting": ["Navidrome", "Reporting"],
  "/navidrome/cleanup": ["Navidrome", "Library Cleanup"],
  "/navidrome/metadata": ["Navidrome", "Metadata Editor"],
  "/collection-completeness": ["Navidrome", "Collection Completeness"],
  "/audiobookshelf": ["Audiobookshelf", "Overview"],
  "/tasks": ["System", "Tasks"],
  "/settings": ["System", "Settings"],
};

export default function App() {
  const [config, setConfig] = useState<AppConfig | null>(null);
  const [navidromeConnected, setNavidromeConnected] = useState(false);
  const [audiobookshelfConnected, setAudiobookshelfConnected] = useState(false);
  const [mobileNavOpen, setMobileNavOpen] = useState(false);
  const [compactShell, setCompactShell] = useState(() =>
    typeof window !== "undefined" ? window.innerWidth <= 1280 : false
  );
  const location = useLocation();

  function refreshConfig() {
    apiGet<AppConfig>("/api/config")
      .then(setConfig)
      .catch(() => setConfig(null));
    apiGet<{ connected: boolean }>("/api/navidrome/status")
      .then((s) => setNavidromeConnected(!!s.connected))
      .catch(() => setNavidromeConnected(false));
    apiGet<{ connected: boolean }>("/api/audiobookshelf/status")
      .then((s) => setAudiobookshelfConnected(!!s.connected))
      .catch(() => setAudiobookshelfConnected(false));
  }

  useEffect(refreshConfig, []);

  useEffect(() => {
    const sync = () => {
      const compact = window.innerWidth <= 1280;
      setCompactShell(compact);
      if (!compact) setMobileNavOpen(false);
    };
    sync();
    window.addEventListener("resize", sync);
    return () => window.removeEventListener("resize", sync);
  }, []);

  const [section, page] = CRUMBS[location.pathname] || ["", ""];

  return (
    <div className={`app ${compactShell ? "app-compact" : ""}`}>
      <Sidebar
        config={config}
        navidromeConnected={navidromeConnected}
        audiobookshelfConnected={audiobookshelfConnected}
        mobileOpen={compactShell && mobileNavOpen}
        onClose={() => setMobileNavOpen(false)}
      />
      <div className="main">
        <header className="topbar">
          <button
            className="btn btn-sm topbar-menu"
            onClick={() => setMobileNavOpen((open) => !open)}
            aria-label={mobileNavOpen ? "Close navigation" : "Open navigation"}
            aria-expanded={mobileNavOpen}
            aria-hidden={!compactShell}
            tabIndex={compactShell ? 0 : -1}
          >
            {mobileNavOpen ? <IconClose /> : <IconMenu />}
          </button>
          <div className="crumbs">
            {section && (
              <>
                <b>{section}</b> &nbsp;/&nbsp;{" "}
              </>
            )}
            {page}
          </div>
          <div className="topbar-spacer" />
          <CommandPalette />
        </header>
        <div className="content">
          <Routes>
            <Route path="/" element={<Dashboard config={config} navidromeConnected={navidromeConnected} />} />
            <Route path="/emby/generator" element={<Generator />} />
            <Route path="/emby/avatar-generator" element={<AvatarGenerator />} />
            <Route path="/emby/collections" element={<Collections />} />
            <Route path="/emby/airing" element={<Airing />} />
            <Route path="/emby/bulk-assign" element={<BulkAssign />} />
            <Route path="/emby/favorites" element={<Favorites />} />
            <Route path="/emby/homescreen" element={<HomescreenEditor />} />
            <Route path="/navidrome/library" element={<Library />} />
            <Route path="/navidrome/reporting" element={<Reporting />} />
            <Route path="/navidrome/cleanup" element={<CoverManager />} />
            <Route path="/navidrome/metadata" element={<Metadata />} />
            <Route path="/collection-completeness" element={<CollectionCompleteness />} />
            <Route path="/audiobookshelf" element={<AudiobookshelfOverview />} />
            <Route path="/tasks" element={<Tasks />} />
            <Route path="/settings" element={<Settings onSaved={refreshConfig} />} />
            <Route path="*" element={<Navigate to="/" replace />} />
          </Routes>
        </div>
      </div>
    </div>
  );
}
