import { useEffect, useState } from "react";
import { api } from "./api/haixun";
import { useAuth } from "./auth/AuthContext";
import { Layout } from "./components/Layout";
import { Button, Card, PageTitle } from "./components/ui";
import { AuthPage } from "./pages/AuthPage";
import { AccountsPage } from "./pages/AccountsPage";
import { DashboardPage } from "./pages/DashboardPage";
import { GapsPage } from "./pages/GapsPage";
import { JobsPage } from "./pages/JobsPage";
import { MissionsPage } from "./pages/MissionsPage";
import { PatrolPage } from "./pages/PatrolPage";
import { PersonasPage } from "./pages/PersonasPage";
import { PublishPage } from "./pages/PublishPage";
import { SettingsPage } from "./pages/SettingsPage";
import { BrandsPage } from "./pages/BrandsPage";
import { clearOAuthPending, parseOAuthReturn, stashOAuthReturnMessage, stripOAuthReturnFromUrl } from "./lib/threadsOAuth";
import { persistActiveThreadsAccountId } from "./lib/activeAccount";

const validPages = new Set(["dashboard", "accounts", "brands", "publish", "personas", "missions", "patrol", "jobs", "settings", "gaps"]);
const accountRequiredPages = new Set(["publish", "personas", "missions", "patrol"]);

export function App() {
  const { member, loading } = useAuth();
  const [page, setPage] = useState(() => normalizePage(location.hash.replace("#", "")));
  const [accountVersion, setAccountVersion] = useState(0);
  const [accountCount, setAccountCount] = useState<number | null>(null);

  useEffect(() => {
    const onHash = () => setPage(normalizePage(location.hash.replace("#", "")));
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  useEffect(() => {
    const onAccountChanged = () => setAccountVersion((value) => value + 1);
    window.addEventListener("haixun:active-account-changed", onAccountChanged);
    return () => window.removeEventListener("haixun:active-account-changed", onAccountChanged);
  }, []);

  useEffect(() => {
    if (!member) return;
    const result = parseOAuthReturn(window.location.search);
    if (!result) return;

    clearOAuthPending();
    stashOAuthReturnMessage(result.message);
    if (result.accountId) persistActiveThreadsAccountId(result.accountId);
    stripOAuthReturnFromUrl();
    window.location.hash = "accounts";
    setPage("accounts");
    setAccountVersion((value) => value + 1);
    window.dispatchEvent(new CustomEvent("haixun:active-account-changed"));
  }, [member]);

  useEffect(() => {
    if (!member) {
      setAccountCount(null);
      return;
    }
    let alive = true;
    async function loadAccounts() {
      try {
        const data = await api.threadsAccounts();
        if (alive) setAccountCount(data.list?.length || 0);
      } catch {
        if (alive) setAccountCount(0);
      }
    }
    void loadAccounts();
    return () => {
      alive = false;
    };
  }, [member, accountVersion]);

  function navigate(next: string) {
    const normalized = normalizePage(next);
    window.location.hash = normalized;
    setPage(normalized);
  }

  if (loading) {
    return <div className="hx-scene auth-page"><section className="auth-ticket auth-shell-form">載入中...</section></div>;
  }

  if (!member) {
    return <AuthPage />;
  }

  return (
    <Layout active={page} onNavigate={navigate}>
      <div key={`${page}-${accountVersion}`}>{renderPage(page, navigate, accountCount)}</div>
    </Layout>
  );
}

function normalizePage(raw: string) {
  return validPages.has(raw) ? raw : "dashboard";
}

function renderPage(page: string, navigate: (key: string) => void, accountCount: number | null) {
  if (accountRequiredPages.has(page)) {
    if (accountCount === null) {
      return (
        <Card>
          <p className="muted">正在確認 Threads 帳號狀態...</p>
        </Card>
      );
    }
    if (accountCount === 0) {
      return <AccountRequiredPage navigate={navigate} />;
    }
  }
  switch (page) {
    case "accounts":
      return <AccountsPage />;
    case "brands":
      return <BrandsPage />;
    case "publish":
      return <PublishPage />;
    case "personas":
      return <PersonasPage />;
    case "missions":
      return <MissionsPage />;
    case "patrol":
      return <PatrolPage />;
    case "jobs":
      return <JobsPage />;
    case "settings":
      return <SettingsPage />;
    case "gaps":
      return <GapsPage />;
    default:
      return <DashboardPage navigate={navigate} />;
  }
}

function AccountRequiredPage({ navigate }: { navigate: (key: string) => void }) {
  return (
    <div className="page-grid">
      <PageTitle title="先建立 Threads 帳號" subtitle="這個功能需要先有一個經營帳號，才能設定 AI、排程發文、生成內容與追蹤成效。" />
      <Card title="還沒有可用帳號">
        <p className="muted">
          請先到 Threads 帳號頁建立帳號，完成 OAuth 或 API 連線後，巡樓 Console 才能開始發文、分析與跑任務。
        </p>
        <Button variant="primary" onClick={() => navigate("accounts")}>去建立並連線 Threads</Button>
      </Card>
    </div>
  );
}
