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";
import { useI18n } from "../i18n/I18nContext";

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 { t } = useI18n();
  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(t("playbooks.published"));
    } 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(t("playbooks.imported"));
      await load();
    } catch (e) {
      setMsg(e instanceof Error ? e.message : "fail");
    } finally {
      setBusy("");
    }
  }

  return (
    <>
      <PageHeader title={t("playbooks.title")} />
      {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="">{t("playbooks.allKinds")}</option>
            <option value="brief">{t("playbooks.kind.brief")}</option>
            <option value="persona">{t("playbooks.kind.persona")}</option>
            <option value="play">{t("playbooks.kind.play")}</option>
          </select>
          <Input value={niche} onChange={(e) => setNiche(e.target.value)} placeholder={t("playbooks.nichePh")} />
          <label>
            <input type="checkbox" checked={mine} onChange={(e) => setMine(e.target.checked)} /> {t("playbooks.mineOnly")}
          </label>
          <Button type="button" onClick={() => setShowPub((v) => !v)}>
            {showPub ? t("playbooks.cancel") : t("playbooks.publish")}
          </Button>
        </div>
        {showPub ? (
          <Card title={t("playbooks.publishCard")}>
            <div className="hb-stack">
              <select
                value={form.kind}
                onChange={(e) => setForm((f) => ({ ...f, kind: e.target.value }))}
              >
                <option value="brief">{t("playbooks.kind.brief")}</option>
                <option value="persona">{t("playbooks.kind.persona")}</option>
                <option value="play">{t("playbooks.kind.play")}</option>
              </select>
              <Input
                label={t("playbooks.fieldTitle")}
                value={form.title}
                onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))}
              />
              <Input
                label={t("playbooks.fieldNiche")}
                value={form.niche}
                onChange={(e) => setForm((f) => ({ ...f, niche: e.target.value }))}
              />
              <Textarea
                label={t("playbooks.fieldBody")}
                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 }))}
                />{" "}
                {t("playbooks.anonymous")}
              </label>
              <Button type="button" disabled={Boolean(busy)} onClick={() => void publish()}>
                {t("playbooks.submit")}
              </Button>
            </div>
          </Card>
        ) : null}
      </div>
      {list.length === 0 ? (
        <EmptyState title={t("playbooks.empty")} />
      ) : (
        <ul className="hb-stack">
          {list.map((p) => (
            <Card key={p.id} title={p.title}>
              <div className="hb-inline-badges">
                <Badge tone="brand">{p.kind === "brief" || p.kind === "persona" || p.kind === "play" ? t(`playbooks.kind.${p.kind}`) : p.kind}</Badge>
                {p.niche ? <Badge tone="neutral">{p.niche}</Badge> : null}
                <Badge tone="neutral">{p.author_label}</Badge>
                <Badge tone="neutral">{t("playbooks.imports", { n: p.import_count })}</Badge>
              </div>
              <pre style={{ whiteSpace: "pre-wrap", fontSize: "var(--hb-text-sm)" }}>{p.body.slice(0, 400)}</pre>
              {!p.mine ? (
                <Button type="button" disabled={busy === p.id} onClick={() => void importPb(p.id)}>
                  {t("playbooks.import")}
                </Button>
              ) : null}
            </Card>
          ))}
        </ul>
      )}
      {/* silence unused */}
      {repos ? null : null}
    </>
  );
}
