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

type Bench = {
  available: boolean;
  sample_size: number;
  niche: string;
  median_eng_rate: number;
  median_views: number;
  your_eng_rate?: number;
  your_views?: number;
  percentile_hint?: string;
  message?: string;
};

export function BenchmarkPage() {
  const [niche, setNiche] = useState("general");
  const [data, setData] = useState<Bench | null>(null);
  const [err, setErr] = useState("");

  const load = useCallback(async () => {
    setErr("");
    try {
      const q = new URLSearchParams({ niche });
      setData(await apiRequest<Bench>(`/api/v1/benchmark?${q}`));
    } catch (e) {
      setErr(e instanceof Error ? e.message : "fail");
    }
  }, [niche]);

  useEffect(() => {
    void load();
  }, [load]);

  return (
    <>
      <PageHeader title="同利基基準" description="匿名聚合中位數（樣本≥5 才顯示）" />
      <div style={{ display: "flex", gap: "0.5rem", marginBottom: "1rem" }}>
        <Input value={niche} onChange={(e) => setNiche(e.target.value)} placeholder="niche" />
        <Button type="button" onClick={() => void load()}>
          查詢
        </Button>
      </div>
      {err ? <p className="hb-form-error">{err}</p> : null}
      {data ? (
        <Card>
          <p>利基：{data.niche} · 樣本 {data.sample_size}</p>
          {data.available ? (
            <>
              <p>
                中位互動率 {(data.median_eng_rate * 100).toFixed(2)}% · 中位瀏覽{" "}
                {data.median_views.toFixed(0)}
              </p>
              <p>
                你的互動率 {((data.your_eng_rate ?? 0) * 100).toFixed(2)}% · 均覽{" "}
                {(data.your_views ?? 0).toFixed(0)}
              </p>
              <p className="text-muted">{data.percentile_hint}</p>
            </>
          ) : (
            <p className="text-muted">{data.message || "樣本不足"}</p>
          )}
        </Card>
      ) : null}
    </>
  );
}
