import { type ReactNode, useEffect, useState } from "react";
import {
  NavLink,
  Navigate,
  Route,
  Routes,
  useLocation,
} from "react-router-dom";
import { apiFetch, clearSession, getToken, getUsername } from "./api";
import LoginPage from "./pages/Login";
import MonitorPage from "./pages/Monitor";
import SettingsPage from "./pages/Settings";
import StatsPage from "./pages/Stats";

function formatBeijingTime(ms: number): string {
  return new Date(ms).toLocaleString("zh-CN", {
    timeZone: "Asia/Shanghai",
    hour12: false,
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
}

function BeijingClock() {
  const [nowMs, setNowMs] = useState(() => Date.now());
  useEffect(() => {
    const t = window.setInterval(() => setNowMs(Date.now()), 1000);
    return () => window.clearInterval(t);
  }, []);
  return (
    <div className="header-beijing-time" title="Asia/Shanghai">
      <span className="header-beijing-label">北京时间</span>
      <span className="mono header-beijing-value">{formatBeijingTime(nowMs)}</span>
    </div>
  );
}

function Shell({ children }: { children: ReactNode }) {
  const user = getUsername();
  const [lanClient, setLanClient] = useState(false);

  useEffect(() => {
    apiFetch<{ lan_client?: boolean }>("/api/auth/me")
      .then((m) => setLanClient(!!m.lan_client))
      .catch(() => setLanClient(false));
  }, []);

  return (
    <div className="shell">
      <header className="header">
        <div className="header-top">
          <div className="header-title-wrap">
            <div className="header-title">对冲舰队指挥中心</div>
            <div className="header-subtitle">—— 比特骆驼定制开发</div>
          </div>
        </div>
        <div className="header-bar">
          <nav className="nav">
            <NavLink to="/monitor" className={({ isActive }) => (isActive ? "active" : "")}>
              监控区
            </NavLink>
            <NavLink to="/stats" className={({ isActive }) => (isActive ? "active" : "")}>
              数据统计
            </NavLink>
            <NavLink to="/settings" className={({ isActive }) => (isActive ? "active" : "")}>
              系统设置
            </NavLink>
          </nav>
          <div className="header-right">
            <BeijingClock />
            {!lanClient ? (
              <>
                <span className="meta">{user}</span>
                <button
                  type="button"
                  className="btn ghost"
                  onClick={() => {
                    clearSession();
                    window.location.href = "/login";
                  }}
                >
                  退出
                </button>
              </>
            ) : null}
          </div>
        </div>
      </header>
      <main className="main">{children}</main>
    </div>
  );
}

/** 监控页保活：切设置/统计不断 SSE、不丢卡片状态 */
function AuthedPages() {
  const loc = useLocation();
  const onMonitor =
    loc.pathname === "/" ||
    loc.pathname === "/monitor" ||
    loc.pathname.startsWith("/monitor/");
  const onStats =
    loc.pathname === "/stats" || loc.pathname.startsWith("/stats/");
  const onSettings =
    loc.pathname === "/settings" || loc.pathname.startsWith("/settings/");
  return (
    <Shell>
      <div className={onMonitor ? "page-pane" : "page-pane hidden"} aria-hidden={!onMonitor}>
        <MonitorPage />
      </div>
      <div className={onStats ? "page-pane" : "page-pane hidden"} aria-hidden={!onStats}>
        <StatsPage />
      </div>
      <div className={onSettings ? "page-pane" : "page-pane hidden"} aria-hidden={!onSettings}>
        <SettingsPage />
      </div>
      {!onMonitor && !onStats && !onSettings ? (
        <Navigate to="/monitor" replace />
      ) : null}
    </Shell>
  );
}

function RequireAuth({ children }: { children: ReactNode }) {
  if (!getToken()) return <Navigate to="/login" replace />;
  return <>{children}</>;
}

export default function App() {
  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route
        path="/*"
        element={
          <RequireAuth>
            <AuthedPages />
          </RequireAuth>
        }
      />
    </Routes>
  );
}
