import { useState, useEffect } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { OverviewPage } from "./components/overview/OverviewPage";
import { Dashboard } from "./components/dashboard/Dashboard";
import { ProjectModal } from "./components/dashboard/ProjectModal";
import { DevToolsPage } from "./components/devtools/DevToolsPage";
import { ProxyPage } from "./components/proxy/ProxyPage";
import { SettingsPage } from "./components/settings/SettingsPage";
import { Sidebar, type Page } from "./components/layout/Sidebar";
import { Toast } from "./components/ui/Toast";
import LoginPage from "./components/auth/LoginPage";
import { githubGetAccount, githubLogout, type GitAccount } from "./lib/commands";
import { useSpacesSync } from "./hooks/useSpacesSync";
import { useUIStore } from "./store/ui";
import { check as checkUpdate } from "@tauri-apps/plugin-updater";

export default function App() {
  const [page, setPage] = useState<Page>("overview");
  const [account, setAccount] = useState<GitAccount | null | undefined>(undefined);
  const qc = useQueryClient();
  const showToast = useUIStore((s) => s.showToast);

  useEffect(() => {
    githubGetAccount().then(setAccount).catch(() => setAccount(null));
  }, []);

  // 启动时静默检查更新
  useEffect(() => {
    checkUpdate()
      .then((update) => {
        if (update?.available) {
          showToast(`🆕 发现新版本 v${update.version}，前往「设置」页更新`);
        }
      })
      .catch(() => {}); // 静默失败，不打扰用户
  }, []);

  const handleLogout = async () => {
    await githubLogout();
    qc.clear();
    setAccount(null);
  };

  const { data: spacesJson } = useSpacesSync(account !== null && account !== undefined);

  if (account === undefined) return null;

  if (account === null) {
    return (
      <div className="min-h-screen bg-zinc-900 text-white flex flex-col">
        <LoginPage onLogin={setAccount} />
        <Toast />
      </div>
    );
  }

  return (
    <div className="h-screen flex overflow-hidden">
      <Sidebar
        account={account}
        onLogout={handleLogout}
        page={page}
        onPageChange={setPage}
      />

      <main className="flex-1 overflow-auto bg-gray-50">
        {page === "overview"  && <OverviewPage />}
        {page === "dashboard" && <Dashboard spacesJson={spacesJson ?? null} />}
        {page === "devtools"  && <DevToolsPage />}
        {page === "proxy"     && <ProxyPage />}
        {page === "settings"  && <SettingsPage />}
      </main>

      <ProjectModal />
      <Toast />
    </div>
  );
}
