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

export function StyleQuizPage() {
  const [samples, setSamples] = useState("");
  const [result, setResult] = useState<{
    tone: string;
    rhythm: string;
    hooks: string;
    avoid: string;
    summary: string;
    tags: 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/style-quiz", {
        method: "POST",
        body: { samples },
      });
      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">免登入：貼上幾則你的 Threads 貼文，立刻看語氣與節奏。</p>
      <Card>
        <Textarea label="貼文樣本" rows={8} value={samples} onChange={(e) => setSamples(e.target.value)} />
        <Button type="button" disabled={busy || !samples.trim()} onClick={() => void run()}>
          {busy ? "分析中…" : "開始分析"}
        </Button>
      </Card>
      {err ? <p className="hb-form-error">{err}</p> : null}
      {result ? (
        <Card title="結果">
          <p>{result.summary}</p>
          <ul>
            <li>語氣：{result.tone}</li>
            <li>節奏：{result.rhythm}</li>
            <li>鉤子：{result.hooks}</li>
            <li>注意：{result.avoid}</li>
          </ul>
          <p className="text-muted">{result.signup_hint}</p>
          <Link to="/login">
            <Button type="button">登入巡樓</Button>
          </Link>
        </Card>
      ) : null}
    </div>
  );
}
