import { useCallback, useEffect, useState } from "react";
import { apiFetch } from "../api";

type FleetStatsRow = {
  id: number;
  name: string;
  ok: boolean;
  error?: string | null;
  initial_funds?: number | null;
  latest_funds?: number | null;
  groups?: number | null;
  fees_perp?: number | null;
  fees_option?: number | null;
  total_fees?: number | null;
  max_single_loss?: number | null;
  loss_streak?: number | null;
  total_pnl?: number | null;
};

function fmt(v: unknown, digits = 4): string {
  if (v == null || v === "") return "—";
  const n = Number(v);
  if (!Number.isFinite(n)) return String(v);
  return n.toFixed(digits);
}

function pnlClass(v: unknown): string {
  const n = Number(v);
  if (!Number.isFinite(n) || n === 0) return "pnl-flat";
  return n > 0 ? "pnl-pos" : "pnl-neg";
}

export default function StatsPage() {
  const [fleetStats, setFleetStats] = useState<FleetStatsRow[]>([]);
  const [fleetStatsErr, setFleetStatsErr] = useState("");
  const [fleetStatsLoading, setFleetStatsLoading] = useState(false);

  const refreshStats = useCallback(async () => {
    setFleetStatsLoading(true);
    try {
      const r = await apiFetch<{ nodes: FleetStatsRow[] }>("/api/nodes/stats/all");
      setFleetStats(r.nodes || []);
      setFleetStatsErr("");
    } catch (ex) {
      setFleetStatsErr(ex instanceof Error ? ex.message : String(ex));
    } finally {
      setFleetStatsLoading(false);
    }
  }, []);

  useEffect(() => {
    void refreshStats();
    const id = window.setInterval(() => void refreshStats(), 60_000);
    return () => window.clearInterval(id);
  }, [refreshStats]);

  const okRows = fleetStats.filter((r) => r.ok);
  const sum = (key: keyof FleetStatsRow) =>
    okRows.reduce((a, r) => a + (Number(r[key]) || 0), 0);
  const maxLoss = okRows.length
    ? Math.min(0, ...okRows.map((r) => Number(r.max_single_loss) || 0))
    : 0;

  return (
    <div>
      <div className="toolbar stats-toolbar">
        <h2>数据统计</h2>
        <div className="toolbar-actions">
          <button
            type="button"
            className="btn ghost"
            disabled={fleetStatsLoading}
            onClick={() => void refreshStats()}
          >
            {fleetStatsLoading ? "加载中…" : "刷新统计"}
          </button>
        </div>
      </div>
      {fleetStatsErr ? <div className="err soft">{fleetStatsErr}</div> : null}
      {fleetStats.length ? (
        <div className="monitor-table-wrap">
          <table className="monitor-table stats-table">
            <thead>
              <tr>
                <th>机器名</th>
                <th>初始资金</th>
                <th>最新资金</th>
                <th>轮次</th>
                <th>永续手续费</th>
                <th>期权手续费</th>
                <th>手续费合计</th>
                <th>单笔最大亏损</th>
                <th>连亏次数</th>
                <th>盈亏</th>
              </tr>
            </thead>
            <tbody>
              {fleetStats.map((row) => (
                <tr key={row.id}>
                  <td>
                    <strong className="machine-name">{row.name}</strong>
                    {!row.ok && row.error ? (
                      <div className="meta" title={row.error}>
                        拉取失败
                      </div>
                    ) : null}
                  </td>
                  <td className="mono">
                    {row.ok ? fmt(row.initial_funds ?? 0, 2) : "—"}
                  </td>
                  <td className="mono">
                    {row.ok ? fmt(row.latest_funds ?? 0, 2) : "—"}
                  </td>
                  <td className="mono">
                    {row.groups != null ? row.groups : "—"}
                  </td>
                  <td className="mono">
                    {row.fees_perp != null ? fmt(row.fees_perp, 4) : "—"}
                  </td>
                  <td className="mono">
                    {row.fees_option != null ? fmt(row.fees_option, 4) : "—"}
                  </td>
                  <td className="mono">
                    {row.total_fees != null ? fmt(row.total_fees, 4) : "—"}
                  </td>
                  <td className={`mono ${pnlClass(row.max_single_loss)}`}>
                    {row.ok ? fmt(row.max_single_loss ?? 0, 2) : "—"}
                  </td>
                  <td className="mono">
                    {row.ok ? String(row.loss_streak ?? 0) : "—"}
                  </td>
                  <td className={`mono ${pnlClass(row.total_pnl)}`}>
                    {row.total_pnl != null ? fmt(row.total_pnl, 2) : "—"}
                  </td>
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr className="stats-total-row">
                <td>
                  <strong>合计</strong>
                  <span className="meta">
                    {" "}
                    ({okRows.length}/{fleetStats.length})
                  </span>
                </td>
                <td className="mono">{fmt(sum("initial_funds"), 2)}</td>
                <td className="mono">{fmt(sum("latest_funds"), 2)}</td>
                <td className="mono">{sum("groups")}</td>
                <td className="mono">{fmt(sum("fees_perp"), 4)}</td>
                <td className="mono">{fmt(sum("fees_option"), 4)}</td>
                <td className="mono">{fmt(sum("total_fees"), 4)}</td>
                <td className={`mono ${pnlClass(maxLoss)}`}>
                  {fmt(maxLoss, 2)}
                </td>
                <td className="mono">—</td>
                <td className={`mono ${pnlClass(sum("total_pnl"))}`}>
                  {fmt(sum("total_pnl"), 2)}
                </td>
              </tr>
            </tfoot>
          </table>
        </div>
      ) : (
        <p className="meta">
          {fleetStatsLoading ? "正在拉取各策略机统计…" : "暂无统计数据"}
        </p>
      )}
    </div>
  );
}
