import { useState } from "react";
import { Link } from "react-router-dom";
import { Button, Card, Input, Textarea } from "../../components/ui";
import { apiRequest } from "../../data/live/http";
import { useI18n } from "../../i18n/I18nContext";

export function PainKeywordsPage() {
  const { t } = useI18n();
  const [brief, setBrief] = useState("");
  const [audience, setAudience] = useState("");
  const [result, setResult] = useState<{
    keywords: string[];
    pains: string[];
    scan_terms: string[];
    summary: string;
    signup_hint: string;
  } | null>(null);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");

  async function run() {
    setBusy(true);
    setErr("");
    try {
      const data = await apiRequest<NonNullable<typeof result>>("/api/v1/public/tools/pain-keywords", {
        method: "POST",
        body: { product_brief: brief, audience },
        // 免登入端點：不要把會員 JWT 送出去，也不要在 401 時觸發 refresh。
        auth: false,
      });
      setResult(data);
    } catch (e) {
      setErr(e instanceof Error ? e.message : "fail");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="hb-main__inner" style={{ maxWidth: 640, margin: "2rem auto", padding: "0 1rem" }}>
      <h1>{t("tools.pain.title")}</h1>
      <p className="text-muted">{t("tools.pain.subtitle")}</p>
      <Card>
        <Textarea label={t("tools.pain.brief")} rows={5} value={brief} onChange={(e) => setBrief(e.target.value)} />
        <Input label={t("tools.pain.audience")} value={audience} onChange={(e) => setAudience(e.target.value)} />
        <Button type="button" disabled={busy || !brief.trim()} onClick={() => void run()}>
          {busy ? t("tools.pain.running") : t("tools.pain.run")}
        </Button>
      </Card>
      {err ? <p className="hb-form-error">{err}</p> : null}
      {result ? (
        <Card title={t("tools.pain.result")}>
          <p>{result.summary}</p>
          <p>
            <strong>{t("tools.pain.keywords")}</strong>：{result.keywords.join("、")}
          </p>
          <p>
            <strong>{t("tools.pain.pains")}</strong>：{result.pains.join("、")}
          </p>
          <p>
            <strong>{t("tools.pain.scan")}</strong>：{result.scan_terms.join("、")}
          </p>
          <p className="text-muted">{result.signup_hint}</p>
          <Link to="/login">
            <Button type="button">{t("tools.pain.login")}</Button>
          </Link>
        </Card>
      ) : null}
    </div>
  );
}
