import { lazy, Suspense, useEffect, useMemo, useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { PageHeader } from "../components/layout/PageHeader";
import { Select } from "../components/ui";
import { useData, useRepos } from "../data/DataContext";
import type { Persona, ThreadsAccount } from "../domain/types";
import { useI18n } from "../i18n/I18nContext";
import { isPersonaReady, personaOptionLabel } from "../lib/personaPrompt";

const ComposerPanel = lazy(() => import("./studio/ComposerPanel").then((m) => ({ default: m.ComposerPanel })));
const InspirePanel = lazy(() => import("./studio/InspirePanel").then((m) => ({ default: m.InspirePanel })));
const MentionsPanel = lazy(() => import("./studio/MentionsPanel").then((m) => ({ default: m.MentionsPanel })));
const OwnPostsPanel = lazy(() => import("./studio/OwnPostsPanel").then((m) => ({ default: m.OwnPostsPanel })));
const PlaysPanel = lazy(() => import("./studio/PlaysPanel").then((m) => ({ default: m.PlaysPanel })));

export type StudioTab = "posts" | "mentions" | "compose" | "plays" | "inspire";

const TAB_KEYS: { key: StudioTab; labelKey: string }[] = [
  { key: "posts", labelKey: "studio.tab.posts" },
  { key: "mentions", labelKey: "studio.tab.mentions" },
  { key: "compose", labelKey: "studio.tab.compose" },
  { key: "plays", labelKey: "studio.tab.plays" },
  { key: "inspire", labelKey: "studio.tab.inspire" },
];

export function StudioPage() {
  const repos = useRepos();
  const { tick } = useData();
  const { t } = useI18n();
  const [params, setParams] = useSearchParams();

  const [accounts, setAccounts] = useState<ThreadsAccount[]>([]);
  const [personas, setPersonas] = useState<Persona[]>([]);
  const [accountId, setAccountId] = useState("");
  const [personaId, setPersonaId] = useState("");
  const [activeBrandLabel, setActiveBrandLabel] = useState("");

  const tab = (params.get("tab") as StudioTab) || "posts";
  const setTab = (next: StudioTab) => {
    const p = new URLSearchParams(params);
    p.set("tab", next);
    // 清掉仿寫／外連殘留 query，避免卡在 from=own-post&mimic=1
    p.delete("from");
    p.delete("mimic");
    p.delete("text");
    setParams(p, { replace: true });
  };

  useEffect(() => {
    void (async () => {
      const [accList, personaList, active, brandId, brands] = await Promise.all([
        repos.accounts.list(),
        repos.personas.list(),
        repos.personas.getActiveId(),
        repos.scout.getActiveBrandId(),
        repos.scout.listBrands(),
      ]);
      const usable = accList.filter((a) => a.is_usable);
      setAccounts(usable.length ? usable : accList);
      setPersonas(personaList);
      setAccountId((cur) => cur || usable[0]?.id || accList[0]?.id || "");
      setPersonaId((cur) => cur || active || personaList[0]?.id || "");
      const brand = brands.find((b) => b.id === brandId);
      setActiveBrandLabel(brand?.display_name || "");
    })();
  }, [repos, tick]);

  const personaReady = useMemo(
    () => isPersonaReady(personas.find((p) => p.id === personaId)),
    [personas, personaId],
  );

  useEffect(() => {
    if (!TAB_KEYS.some((item) => item.key === tab)) {
      setTab("posts");
    }
  }, [tab]); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <>
      <PageHeader title={t("studio.title")} />

      <div className="hb-studio-bar">
        <Select
          label={t("studio.account")}
          value={accountId}
          onChange={(e) => setAccountId(e.target.value)}
        >
          {accounts.map((a) => (
            <option key={a.id} value={a.id}>
              {a.display_name} · @{a.username}
            </option>
          ))}
        </Select>
        <Select
          label={t("studio.persona")}
          value={personaId}
          onChange={(e) => {
            setPersonaId(e.target.value);
            void repos.personas.setActiveId(e.target.value);
          }}
        >
          {personas.map((p) => (
            <option key={p.id} value={p.id}>
              {personaOptionLabel(p)}
            </option>
          ))}
        </Select>
        <p className="text-muted hb-studio-bar__hint">
          {personaReady ? t("studio.personaReady") : t("studio.personaNotReady")}
          {activeBrandLabel ? ` · ${activeBrandLabel}` : ""}
          {" · "}
          <Link to="/app/crew">{t("nav.crew")}</Link>
          {" · "}
          <Link to="/app/brands">{t("nav.brands")}</Link>
        </p>
      </div>

      <div className="hb-tabs" role="tablist">
        {TAB_KEYS.map((item) => (
          <button
            key={item.key}
            type="button"
            className={`hb-tab ${tab === item.key ? "is-active" : ""}`}
            onClick={() => setTab(item.key)}
          >
            {t(item.labelKey)}
          </button>
        ))}
      </div>

      <Suspense fallback={<div className="hb-route-loading hb-route-loading--content" role="status" aria-label="Loading" />}>
        {tab === "posts" ? (
          <OwnPostsPanel accountId={accountId} personaId={personaId} accounts={accounts} personas={personas} />
        ) : null}
        {tab === "mentions" ? (
          <MentionsPanel accountId={accountId} personaId={personaId} accounts={accounts} personas={personas} />
        ) : null}
        {tab === "compose" ? (
          <ComposerPanel accountId={accountId} personaId={personaId} personaReady={personaReady} />
        ) : null}
        {tab === "plays" ? <PlaysPanel accountId={accountId} personaId={personaId} personas={personas} /> : null}
        {tab === "inspire" ? (
          <InspirePanel accountId={accountId} personaId={personaId} personaReady={personaReady} />
        ) : null}
      </Suspense>
    </>
  );
}
