import { useCallback, useEffect, useState } from "react";
import { PageHeader } from "../components/layout/PageHeader";
import { Badge, Button, Card, EmptyState, Input, Textarea } from "../components/ui";
import { useRepos } from "../data/DataContext";
import { apiRequest } from "../data/live/http";

type Playbook = {
  id: string;
  kind: string;
  title: string;
  niche: string;
  body: string;
  anonymous: boolean;
  author_label: string;
  import_count: number;
  created_at: number;
  mine?: boolean;
};

export function PlaybooksPage() {
  const repos = useRepos();
  const [list, setList] = useState<Playbook[]>([]);
  const [mine, setMine] = useState(false);
  const [kind, setKind] = useState("");
  const [niche, setNiche] = useState("");
  const [busy, setBusy] = useState("");
  const [msg, setMsg] = useState("");
  const [showPub, setShowPub] = useState(false);
  const [form, setForm] = useState({ kind: "brief", title: "", niche: "", body: "", anonymous: true });

  const load = useCallback(async () => {
    const q = new URLSearchParams({ page: "1", pageSize: "50" });
    if (kind) q.set("kind", kind);
    if (niche) q.set("niche", niche);
    if (mine) q.set("mine", "true");
    const data = await apiRequest<{ list?: Playbook[] }>(`/api/v1/playbooks?${q}`);
    setList(data.list ?? []);
  }, [kind, niche, mine]);

  useEffect(() => {
    void load().catch((e) => setMsg(e instanceof Error ? e.message : "load fail"));
  }, [load]);

  async function publish() {
    setBusy("pub");
    try {
      await apiRequest("/api/v1/playbooks", { method: "POST", body: form });
      setShowPub(false);
      setForm({ kind: "brief", title: "", niche: "", body: "", anonymous: true });
      await load();
      setMsg("已發布");
    } catch (e) {
      setMsg(e instanceof Error ? e.message : "fail");
    } finally {
      setBusy("");
    }
  }

  async function importPb(id: string) {
    setBusy(id);
    try {
      await apiRequest(`/api/v1/playbooks/${id}/import`, { method: "POST", body: {} });
      setMsg("已引用到我的 playbook");
      await load();
    } catch (e) {
      setMsg(e instanceof Error ? e.message : "fail");
    } finally {
      setBusy("");
    }
  }

  return (
    <>
      <PageHeader title="Playbook 市集" description="分享／引用海巡 brief、人設、劇本模板" />
      {msg ? <p className="text-muted">{msg}</p> : null}
      <div className="hb-stack" style={{ marginBottom: "1rem" }}>
        <div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
          <select value={kind} onChange={(e) => setKind(e.target.value)}>
            <option value="">全部類型</option>
            <option value="brief">海巡 brief</option>
            <option value="persona">人設</option>
            <option value="play">互回劇本</option>
          </select>
          <Input value={niche} onChange={(e) => setNiche(e.target.value)} placeholder="利基（保養／母嬰…）" />
          <label>
            <input type="checkbox" checked={mine} onChange={(e) => setMine(e.target.checked)} /> 只看我的
          </label>
          <Button type="button" onClick={() => setShowPub((v) => !v)}>
            {showPub ? "取消" : "發布模板"}
          </Button>
        </div>
        {showPub ? (
          <Card title="發布">
            <div className="hb-stack">
              <select
                value={form.kind}
                onChange={(e) => setForm((f) => ({ ...f, kind: e.target.value }))}
              >
                <option value="brief">brief</option>
                <option value="persona">persona</option>
                <option value="play">play</option>
              </select>
              <Input
                label="標題"
                value={form.title}
                onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))}
              />
              <Input
                label="利基"
                value={form.niche}
                onChange={(e) => setForm((f) => ({ ...f, niche: e.target.value }))}
              />
              <Textarea
                label="內容"
                rows={6}
                value={form.body}
                onChange={(e) => setForm((f) => ({ ...f, body: e.target.value }))}
              />
              <label>
                <input
                  type="checkbox"
                  checked={form.anonymous}
                  onChange={(e) => setForm((f) => ({ ...f, anonymous: e.target.checked }))}
                />{" "}
                匿名
              </label>
              <Button type="button" disabled={Boolean(busy)} onClick={() => void publish()}>
                送出
              </Button>
            </div>
          </Card>
        ) : null}
      </div>
      {list.length === 0 ? (
        <EmptyState title="尚無模板" />
      ) : (
        <ul className="hb-stack">
          {list.map((p) => (
            <Card key={p.id} title={p.title}>
              <div className="hb-inline-badges">
                <Badge tone="brand">{p.kind}</Badge>
                {p.niche ? <Badge tone="neutral">{p.niche}</Badge> : null}
                <Badge tone="neutral">{p.author_label}</Badge>
                <Badge tone="neutral">引用 {p.import_count}</Badge>
              </div>
              <pre style={{ whiteSpace: "pre-wrap", fontSize: "0.85rem" }}>{p.body.slice(0, 400)}</pre>
              {!p.mine ? (
                <Button type="button" disabled={busy === p.id} onClick={() => void importPb(p.id)}>
                  引用
                </Button>
              ) : null}
            </Card>
          ))}
        </ul>
      )}
      {/* silence unused */}
      {repos ? null : null}
    </>
  );
}
