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

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 { t } = useI18n();
  const [data, setData] = useState<Bench | null>(null);
  const [err, setErr] = useState("");

  // 利基維度還沒有真來源（帳號／品牌都沒存利基），先只比全站桶；
  // 給輸入框只會讓使用者打出一個永遠「樣本不足」的空桶。
  const load = useCallback(async () => {
    setErr("");
    try {
      setData(await apiRequest<Bench>("/api/v1/benchmark"));
    } catch (e) {
      setErr(e instanceof Error ? e.message : "fail");
    }
  }, []);

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

  return (
    <>
      <PageHeader title={t("bench.title")} />
      <div style={{ marginBottom: "1rem" }}>
        <Button type="button" onClick={() => void load()}>
          {t("bench.reload")}
        </Button>
      </div>
      {err ? <p className="hb-form-error">{err}</p> : null}
      {data ? (
        <Card>
          <p>{t("bench.sample", { n: data.sample_size })}</p>
          {data.available ? (
            <>
              <p>
                {t("bench.median", {
                  eng: (data.median_eng_rate * 100).toFixed(2),
                  views: data.median_views.toFixed(0),
                })}
              </p>
              <p>
                {t("bench.yours", {
                  eng: ((data.your_eng_rate ?? 0) * 100).toFixed(2),
                  views: (data.your_views ?? 0).toFixed(0),
                })}
              </p>
              <p className="text-muted">{data.percentile_hint}</p>
            </>
          ) : (
            <p className="text-muted">{data.message || t("bench.insufficient")}</p>
          )}
        </Card>
      ) : null}
    </>
  );
}
