"use client";

import { useEffect, useState } from "react";
import { api, type MetricsResponse } from "../lib/api";

export function MetricsPanel({ code }: { code: string }) {
  const [m, setM] = useState<MetricsResponse | null>(null);
  const [err, setErr] = useState<string | null>(null);

  useEffect(() => {
    let alive = true;
    api
      .metrics(code, 30)
      .then((r) => {
        if (alive) setM(r);
      })
      .catch((e) => {
        if (alive) setErr(e instanceof Error ? e.message : String(e));
      });
    return () => {
      alive = false;
    };
  }, [code]);

  if (err) return <div className="text-xs text-red-400">메트릭 로딩 실패: {err}</div>;
  if (!m) return <div className="text-xs text-zinc-500">메트릭 로딩 중…</div>;

  const rows = m.by_model_horizon ?? [];
  if (!rows.length) {
    return (
      <div className="text-xs text-zinc-500">
        최근 30일 매칭된 예측 결과가 아직 없습니다. (매칭 배치는 평일 16:30 KST 에 실행)
      </div>
    );
  }

  return (
    <div className="rounded-md border border-zinc-800 bg-zinc-900/40 p-4">
      <div className="mb-2 text-sm font-medium text-zinc-200">최근 30일 모델 성능</div>
      <table className="w-full text-left text-sm">
        <thead className="text-xs text-zinc-500">
          <tr>
            <th className="py-1">모델</th>
            <th>+거래일</th>
            <th>표본 수</th>
            <th>방향 적중률</th>
            <th>평균 절대오차 (MAE)</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-zinc-800">
          {rows.map((r, i) => (
            <tr key={i}>
              <td className="py-1">{r.model}</td>
              <td>+{r.horizon}</td>
              <td>{r.n}</td>
              <td>{r.hit_rate != null ? `${(r.hit_rate * 100).toFixed(1)}%` : "-"}</td>
              <td>{r.mae != null ? r.mae.toLocaleString(undefined, { maximumFractionDigits: 1 }) : "-"}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
