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

export function PainKeywordsPage() {
  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 },
      });
      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>痛點關鍵字產生器</h1>
      <p className="text-muted">免登入：描述產品，產出海巡可用的掃描詞與痛點。</p>
      <Card>
        <Textarea label="產品簡述" rows={5} value={brief} onChange={(e) => setBrief(e.target.value)} />
        <Input label="受眾（選填）" value={audience} onChange={(e) => setAudience(e.target.value)} />
        <Button type="button" disabled={busy || !brief.trim()} onClick={() => void run()}>
          {busy ? "產生中…" : "產生關鍵字"}
        </Button>
      </Card>
      {err ? <p className="hb-form-error">{err}</p> : null}
      {result ? (
        <Card title="結果">
          <p>{result.summary}</p>
          <p>
            <strong>關鍵字</strong>：{result.keywords.join("、")}
          </p>
          <p>
            <strong>痛點</strong>：{result.pains.join("、")}
          </p>
          <p>
            <strong>掃描詞</strong>：{result.scan_terms.join("、")}
          </p>
          <p className="text-muted">{result.signup_hint}</p>
          <Link to="/login">
            <Button type="button">登入巡樓海巡</Button>
          </Link>
        </Card>
      ) : null}
    </div>
  );
}
