"use client";

import PageHeader from "@/components/PageHeader";
import StatCard from "@/components/StatCard";
import { api } from "@/lib/api";
import { pct, usd } from "@/lib/format";
import type { StrategyPerformance } from "@/lib/types";
import { useApi } from "@/lib/useApi";

const GRADE_COLORS: Record<string, string> = {
  A: "bg-bull/20 text-bull",
  B: "bg-accent/20 text-accent",
  C: "bg-gold/20 text-gold",
  D: "bg-bear/20 text-bear",
  F: "bg-bear/30 text-bear",
  "—": "bg-ink-700 text-slate-500",
};

function GradeBadge({ grade }: { grade: string }) {
  return (
    <span className={`inline-flex items-center justify-center w-9 h-9 rounded-lg text-lg font-bold ${GRADE_COLORS[grade] ?? GRADE_COLORS["—"]}`}>
      {grade}
    </span>
  );
}

function n(v: number | null | undefined, digits = 2, suffix = ""): string {
  return v === null || v === undefined ? "—" : `${v.toFixed(digits)}${suffix}`;
}

export default function PerformancePage() {
  const perf = useApi(api.performance, 120_000);
  const bench = useApi(() => api.benchmark(30), 120_000);

  const live = perf.live && bench.live;
  const strategies = perf.data?.strategies ?? [];
  const b = bench.data;

  return (
    <div>
      <PageHeader
        title="AI Performance"
        subtitle="Each strategy is graded as a competing agent — evidence over confidence"
        live={live}
      />

      {b && (
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
          <StatCard
            label={`Account (${b.period_days}d)`}
            value={pct(b.account_return_pct)}
            tone={b.account_return_pct >= 0 ? "up" : "down"}
            sub={`${usd(b.realized_pnl)} realized · ${b.trades} trades`}
          />
          <StatCard
            label={`SPY (${b.period_days}d)`}
            value={b.spy_return_pct !== null ? pct(b.spy_return_pct) : "—"}
            sub="Buy-and-hold benchmark"
          />
          <StatCard
            label="vs Benchmark"
            value={b.outperforming === null ? "—" : b.outperforming ? "AHEAD" : "BEHIND"}
            tone={b.outperforming ? "up" : "down"}
            sub="Strategy must beat the index to earn its complexity"
          />
          <StatCard
            label="Strategies Graded"
            value={`${strategies.filter((s) => s.graded).length} / ${strategies.length}`}
            sub={`Needs ${perf.data?.min_trades_for_grade ?? 5}+ closed trades each`}
          />
        </div>
      )}

      <h2 className="text-sm font-semibold uppercase tracking-wider text-slate-500 mb-3">
        Report card
      </h2>
      {perf.loading && !perf.data ? (
        <div className="text-slate-500 animate-pulse">Loading performance…</div>
      ) : strategies.length === 0 ? (
        <div className="card p-6 text-sm text-slate-500">
          No trades yet — grades appear as paper trades close.
        </div>
      ) : (
        <div className="grid lg:grid-cols-2 gap-4">
          {strategies.map((s) => (
            <StrategyCard key={s.strategy} s={s} />
          ))}
        </div>
      )}

      <p className="text-[11px] text-slate-600 mt-4">{perf.data?.note}</p>
    </div>
  );
}

function StrategyCard({ s }: { s: StrategyPerformance }) {
  return (
    <div className="card p-5">
      <div className="flex items-start justify-between mb-4">
        <div>
          <div className="font-semibold text-slate-100 capitalize">
            {s.strategy === "options" ? "Options Momentum" : s.strategy === "swing" ? "Swing Trend-Pullback" : s.strategy}
          </div>
          <div className="text-xs text-slate-500 mt-0.5">
            {s.trades} closed · {s.open_trades} open
            {s.composite_score !== null && (
              <> · composite <span className="font-mono text-slate-300">{s.composite_score}</span></>
            )}
          </div>
        </div>
        <GradeBadge grade={s.grade} />
      </div>

      <div className="grid grid-cols-3 gap-x-4 gap-y-3 text-xs">
        <Metric k="Win rate" v={n(s.win_rate, 1, "%")} />
        <Metric k="Total P&L" v={usd(s.total_pnl)} color={s.total_pnl >= 0 ? "text-bull" : "text-bear"} />
        <Metric k="Avg P&L" v={s.avg_pnl !== null ? usd(s.avg_pnl) : "—"} />
        <Metric k="Expectancy" v={n(s.expectancy_r, 2, "R")} />
        <Metric k="Profit factor" v={n(s.profit_factor)} />
        <Metric k="Max drawdown" v={s.max_drawdown !== null ? usd(s.max_drawdown) : "—"} color="text-bear" />
        <Metric k="Avg hold" v={n(s.avg_hold_hours, 1, "h")} />
        <Metric k="Avg MFE" v={n(s.avg_mfe_r, 2, "R")} color="text-bull" />
        <Metric k="Avg MAE" v={n(s.avg_mae_r, 2, "R")} color="text-bear" />
      </div>

      {s.calibration_error !== null && (
        <div className="mt-4 text-xs text-slate-500 border-t border-ink-800 pt-3">
          Confidence calibration: predictions off by{" "}
          <span className={`font-mono ${s.calibration_error <= 8 ? "text-bull" : "text-gold"}`}>
            {s.calibration_error} pts
          </span>{" "}
          on average {s.calibration_error <= 8 ? "(well calibrated)" : "(recalibrating from outcomes)"}
        </div>
      )}
      {!s.graded && (
        <div className="mt-4 text-xs text-gold border-t border-ink-800 pt-3">
          Not enough closed trades to grade yet — keep paper trading.
        </div>
      )}
    </div>
  );
}

function Metric({ k, v, color = "text-slate-200" }: { k: string; v: string; color?: string }) {
  return (
    <div>
      <div className="text-slate-500">{k}</div>
      <div className={`font-mono mt-0.5 ${color}`}>{v}</div>
    </div>
  );
}
