import { useEffect, useMemo, useState } from "react";
import { api, Persona, PostPerformance, PublishHealth, ThreadsAccount } from "../api/haixun";
import { Button, Card, ErrorText, Field, PageTitle, Select, StatCard } from "../components/ui";
import { shortText } from "../lib/format";
import { buildPublishPageStats } from "../lib/postStats";
import {
  isPublishPageCacheFresh,
  readPublishPageCache,
  writePublishPageCache
} from "../lib/publishPageCache";
import { persistPublishVoicePersonaId, readPublishVoicePersonaId } from "../lib/publishPersona";
import { MentionsInboxPanel } from "./publish/MentionsInboxPanel";
import { OwnPostsHub } from "./publish/OwnPostsHub";

function formatSyncTime(ms: number) {
  return new Date(ms).toLocaleString("zh-TW", { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit" });
}

type SyncPhase = "idle" | "threads" | "formulas" | "done";

function SyncProgressBanner({
  phase,
  formulasLoading,
  postCount,
  formulaCount,
  lastSyncedAt
}: {
  phase: SyncPhase;
  formulasLoading: boolean;
  postCount: number;
  formulaCount: number;
  lastSyncedAt: number | null;
}) {
  const syncing = phase === "threads" || phase === "formulas" || formulasLoading;
  const threadsDone = phase === "formulas" || phase === "done" || (!syncing && Boolean(lastSyncedAt));
  const formulasDone = phase === "done" && !formulasLoading;

  if (!syncing && !lastSyncedAt) return null;

  return (
    <div
      className={`hx-sync-banner${syncing ? " hx-sync-banner--active" : " hx-sync-banner--done"}`}
      role="status"
      aria-live="polite"
    >
      {syncing ? (
        <>
          <span className="hx-sync-banner__spinner" aria-hidden="true" />
          <div className="hx-sync-banner__body">
            <strong>正在同步資料…</strong>
            <ul className="hx-sync-steps">
              <li className={phase === "threads" ? "is-active" : threadsDone ? "is-done" : ""}>
                <span className="hx-sync-steps__mark" aria-hidden="true" />
                向 Threads API 拉貼文成效（讚、回覆、瀏覽…）
              </li>
              <li className={phase === "formulas" || formulasLoading ? "is-active" : formulasDone ? "is-done" : ""}>
                <span className="hx-sync-steps__mark" aria-hidden="true" />
                從資料庫載入儲存覆盤（GET，不重打 AI）
              </li>
            </ul>
            <p className="hx-sync-banner__hint">
              5 分鐘內會先用本機快照；按右上角「重新同步 Threads」才一定重打 Threads API
            </p>
          </div>
        </>
      ) : (
        <>
          <span className="hx-sync-banner__check" aria-hidden="true">✓</span>
          <div className="hx-sync-banner__body">
            <strong>同步完成</strong>
            <p className="hx-sync-banner__summary">
              {lastSyncedAt ? formatSyncTime(lastSyncedAt) : "—"}
              {" · "}
              {postCount} 篇貼文
              {" · "}
              {formulaCount} 筆儲存覆盤
            </p>
            <p className="hx-sync-banner__hint">顯示本機快照或剛同步的資料；下次進頁若超過 5 分鐘才會更新 Threads API</p>
          </div>
        </>
      )}
    </div>
  );
}

export function PublishPage() {
  const [accounts, setAccounts] = useState<ThreadsAccount[]>([]);
  const [accountId, setAccountId] = useState("");
  const [health, setHealth] = useState<PublishHealth>();
  const [performance, setPerformance] = useState<PostPerformance>();
  const [message, setMessage] = useState("");
  const [error, setError] = useState<unknown>();
  const [pageLoading, setPageLoading] = useState(false);
  const [refreshTick, setRefreshTick] = useState(0);
  const [lastSyncedAt, setLastSyncedAt] = useState<number | null>(null);
  const [syncPhase, setSyncPhase] = useState<SyncPhase>("idle");
  const [formulasLoading, setFormulasLoading] = useState(false);
  const [formulaCount, setFormulaCount] = useState(0);
  const [personas, setPersonas] = useState<Persona[]>([]);
  const [selectedPersonaId, setSelectedPersonaId] = useState(() => readPublishVoicePersonaId());

  const selected = useMemo(() => accounts.find((account) => account.id === accountId), [accounts, accountId]);
  const selectedPersona = useMemo(
    () => personas.find((persona) => persona.id === selectedPersonaId),
    [personas, selectedPersonaId]
  );
  const stats = useMemo(() => buildPublishPageStats(performance, health), [performance, health]);

  function applyCachedSnapshot(id: string) {
    const cache = readPublishPageCache(id);
    if (!cache) return false;
    if (cache.performance) setPerformance(cache.performance);
    if (cache.health) setHealth(cache.health);
    if (cache.cachedAt) setLastSyncedAt(cache.cachedAt);
    return Boolean(cache.performance || cache.health);
  }

  async function fetchAccountSnapshot(id: string) {
    const [healthData, perfData] = await Promise.all([api.publishHealth(id), api.postPerformance(id, 30)]);
    setHealth(healthData);
    setPerformance(perfData);
    const syncedAt = Date.now();
    setLastSyncedAt(syncedAt);
    writePublishPageCache(id, { performance: perfData, health: healthData, cachedAt: syncedAt });
    return syncedAt;
  }

  async function load(nextAccountId = accountId, options?: { notify?: boolean; force?: boolean }) {
    setError(undefined);
    setPageLoading(true);
    try {
      const accountData = await api.threadsAccounts();
      setAccounts(accountData.list || []);
      const id = nextAccountId || accountData.active_account_id || accountData.list?.[0]?.id || "";
      setAccountId(id);
      if (!id) {
        setSyncPhase("idle");
        return;
      }

      const cache = readPublishPageCache(id);
      const hasCache = applyCachedSnapshot(id);
      const shouldFetch =
        options?.force === true || !hasCache || !cache?.cachedAt || !isPublishPageCacheFresh(cache.cachedAt);

      if (!shouldFetch) {
        setSyncPhase("formulas");
        setRefreshTick((tick) => tick + 1);
        if (options?.notify) setMessage("已載入本機快照，未重打 Threads API");
        return;
      }

      setSyncPhase("threads");
      await fetchAccountSnapshot(id);
      setSyncPhase("formulas");
      setRefreshTick((tick) => tick + 1);
      if (options?.notify) setMessage("");
    } catch (err) {
      setError(err);
      setSyncPhase("idle");
    } finally {
      setPageLoading(false);
    }
  }

  useEffect(() => {
    if (syncPhase !== "formulas" || formulasLoading) return;
    setSyncPhase("done");
  }, [syncPhase, formulasLoading]);

  async function refreshPerformance() {
    if (!accountId) return;
    setSyncPhase("threads");
    try {
      await fetchAccountSnapshot(accountId);
      setSyncPhase("formulas");
      setRefreshTick((tick) => tick + 1);
    } catch (err) {
      setError(err);
      setSyncPhase("idle");
      throw err;
    }
  }

  useEffect(() => {
    void load();
  }, []);

  useEffect(() => {
    void api.personas().then((data) => {
      const list = data.list || [];
      setPersonas(list);
      setSelectedPersonaId((current) => {
        if (current && list.some((persona) => persona.id === current)) return current;
        const stored = readPublishVoicePersonaId();
        if (stored && list.some((persona) => persona.id === stored)) return stored;
        return list[0]?.id || "";
      });
    });
  }, []);

  const engagementHint =
    stats.source === "threads_api"
      ? `${stats.postCount7d} 篇貼文 · 讚 ${stats.likes7d} / 回覆 ${stats.replies7d}${stats.views7d ? ` / 瀏覽 ${stats.views7d}` : ""}`
      : `排程發布 ${stats.postCount7d} 篇 · 讚 ${stats.likes7d} / 回覆 ${stats.replies7d}`;

  const queueHint =
    stats.source === "threads_api" && stats.queue7d.postCount > 0
      ? `（排程發布 ${stats.queue7d.postCount} 篇 · 讚 ${stats.queue7d.likes} / 回覆 ${stats.queue7d.replies}）`
      : "";

  return (
    <div className="page-grid">
      <PageTitle
        title="已發貼文管理"
        subtitle="專注管理你已發布的 Threads：回留言、看成效、AI 覆盤爆款公式。排程與自動發文請到文案任務。"
        action={
          <Button loading={pageLoading} onClick={() => void load(accountId, { notify: true, force: true })}>
            重新同步 Threads
          </Button>
        }
      />
      <ErrorText error={error} />
      <SyncProgressBanner
        phase={syncPhase}
        formulasLoading={formulasLoading}
        postCount={performance?.posts?.length ?? 0}
        formulaCount={formulaCount}
        lastSyncedAt={lastSyncedAt}
      />
      {message ? <Card><p>{message}</p></Card> : null}

      <Card>
        <Field label="Threads 帳號">
          <Select value={accountId} onChange={(e) => { setAccountId(e.target.value); void load(e.target.value, { force: false }); }}>
            {accounts.map((account) => (
              <option key={account.id} value={account.id}>{account.display_name || account.username || account.id}</option>
            ))}
          </Select>
        </Field>
      </Card>

      <Card title="回覆人設">
        <Field
          label="Voice Persona"
          hint="全頁共用：@ 提及回覆、留言回覆、AI 覆盤都會依此人設語氣"
        >
          <Select
            value={selectedPersonaId}
            onChange={(e) => {
              const nextId = e.target.value;
              setSelectedPersonaId(nextId);
              persistPublishVoicePersonaId(nextId);
            }}
            disabled={personas.length === 0}
          >
            {personas.length === 0 ? <option value="">尚未建立人設</option> : null}
            {personas.map((persona) => (
              <option key={persona.id} value={persona.id}>
                {persona.display_name || persona.id}
              </option>
            ))}
          </Select>
        </Field>
        {selectedPersona?.persona ? (
          <p className="muted hx-text-sm" style={{ marginTop: 8 }}>
            {shortText(selectedPersona.persona, 160)}
          </p>
        ) : null}
      </Card>

      <div className="grid-3">
        <StatCard
          label="已同步貼文"
          value={performance?.posts?.length ?? 0}
          hint={performance?.username ? `@${performance.username} · Threads API` : "Threads API"}
        />
        <StatCard
          label="近 7 天互動"
          value={stats.interactions7d}
          hint={`${engagementHint}${queueHint}`}
        />
        <StatCard
          label="近 7 天發文"
          value={stats.postCount7d}
          hint={stats.source === "threads_api" ? "依貼文發布時間（API）" : selected?.display_name || selected?.username || "排程發布紀錄"}
        />
      </div>

      <MentionsInboxPanel
        accountId={accountId}
        accountUsername={performance?.username || selected?.username}
        selectedPersonaId={selectedPersonaId}
      />

      <OwnPostsHub
        accountId={accountId}
        performance={performance}
        refreshTick={refreshTick}
        selectedPersonaId={selectedPersonaId}
        onRefresh={refreshPerformance}
        onMessage={setMessage}
        onFormulasLoadingChange={setFormulasLoading}
        onFormulasLoaded={setFormulaCount}
      />
    </div>
  );
}
