"use client";

import { useState } from "react";
import { DirectionBadge } from "@/components/Badge";
import PageHeader from "@/components/PageHeader";
import StatCard from "@/components/StatCard";
import { api } from "@/lib/api";
import { pct, usd } from "@/lib/format";
import type { BacktestResult, Calibration } from "@/lib/types";
import { useApi } from "@/lib/useApi";

function EquityCurve({ data }: { data: number[] }) {
  if (data.length < 2) return null;
  const w = 640, h = 120;
  const min = Math.min(0, ...data);
  const max = Math.max(0, ...data);
  const range = max - min || 1;
  const step = w / (data.length - 1);
  const y = (v: number) => h - ((v - min) / range) * (h - 8) - 4;
  const points = data.map((v, i) => `${(i * step).toFixed(1)},${y(v).toFixed(1)}`).join(" ");
  const up = data[data.length - 1] >= 0;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="w-full h-28">
      <line x1="0" y1={y(0)} x2={w} y2={y(0)} stroke="#2a3550" strokeDasharray="4 4" />
      <polyline points={points} fill="none" stroke={up ? "#22c55e" : "#ef4444"} strokeWidth="2" />
    </svg>
  );
}

export default function BacktestPage() {
  const [days, setDays] = useState(180);
  const [minScore, setMinScore] = useState(60);
  const [horizon, setHorizon] = useState(10);
  const [result, setResult] = useState<BacktestResult | null>(null);
  const [live, setLive] = useState(false);
  const [running, setRunning] = useState(false);
  const calib = useApi<Calibration>(api.calibration);

  const run = async () => {
    setRunning(true);
    const r = await api.runBacktest({ days, min_score: minScore, horizon });
    setResult(r.data);
    setLive(r.live);
    setRunning(false);
  };

  const o = result?.overall;

  return (
    <div>
      <PageHeader
        title="Strategy Backtest"
        subtitle="Walk-forward simulation of the signal strategy — no look-ahead"
        live={result ? live : undefined}
      />

      <div className="card p-4 flex flex-wrap items-end gap-4 mb-6">
        <Param label="History">
          <select value={days} onChange={(e) => setDays(Number(e.target.value))} className="input-base">
            <option value={90}>~4 months</option>
            <option value={180}>~8 months</option>
            <option value={365}>~1.5 years</option>
            <option value={730}>~3 years</option>
          </select>
        </Param>
        <Param label={`Min signal score: ${minScore}`}>
          <input type="range" min={40} max={85} value={minScore}
            onChange={(e) => setMinScore(Number(e.target.value))} className="w-36 accent-sky-400" />
        </Param>
        <Param label={`Max hold: ${horizon} bars`}>
          <input type="range" min={3} max={30} value={horizon}
            onChange={(e) => setHorizon(Number(e.target.value))} className="w-36 accent-sky-400" />
        </Param>
        <button
          onClick={run}
          disabled={running}
          className="text-xs px-5 py-2.5 rounded-lg bg-accent/15 border border-accent/40 text-accent hover:bg-accent/25 disabled:opacity-50"
        >
          {running ? "Simulating…" : "▶ Run Backtest"}
        </button>
      </div>

      {!result && !running && (
        <div className="card p-8 text-sm text-slate-500 text-center">
          Configure parameters and run a backtest. Results are in R-multiples
          (profit relative to initial risk) — an avg R above 0 with profit factor
          above 1.5 suggests an edge worth paper trading.
        </div>
      )}

      {result && o && (
        <>
          <div className="grid grid-cols-2 lg:grid-cols-6 gap-4">
            <StatCard label="Trades" value={String(o.trades)} />
            <StatCard label="Win Rate" value={pct(o.win_rate)} />
            <StatCard label="Avg R" value={o.avg_r.toFixed(2)} tone={o.avg_r >= 0 ? "up" : "down"} />
            <StatCard label="Profit Factor" value={o.profit_factor.toFixed(2)} tone={o.profit_factor >= 1.5 ? "up" : o.profit_factor >= 1 ? "neutral" : "down"} />
            <StatCard label="Total R" value={o.total_r.toFixed(1)} tone={o.total_r >= 0 ? "up" : "down"} />
            <StatCard label="Max DD (R)" value={o.max_drawdown_r.toFixed(1)} tone="down" />
          </div>

          <div className="card p-4 mt-4">
            <div className="text-xs uppercase tracking-wider text-slate-500 mb-2">
              Equity curve (cumulative R)
            </div>
            <EquityCurve data={result.equity_curve_r} />
          </div>

          <div className="grid lg:grid-cols-2 gap-4 mt-4">
            <div className="card overflow-x-auto">
              <div className="px-4 pt-4 text-xs uppercase tracking-wider text-slate-500">Per symbol</div>
              <table className="table-base">
                <thead>
                  <tr><th>Symbol</th><th className="text-right">Trades</th><th className="text-right">Win %</th><th className="text-right">Avg R</th><th className="text-right">Total R</th></tr>
                </thead>
                <tbody>
                  {result.per_symbol.map((s) => (
                    <tr key={s.symbol}>
                      <td className="font-semibold text-slate-100">{s.symbol}</td>
                      <td className="text-right font-mono">{s.trades}</td>
                      <td className="text-right font-mono">{s.win_rate.toFixed(0)}%</td>
                      <td className={`text-right font-mono ${s.avg_r >= 0 ? "text-bull" : "text-bear"}`}>{s.avg_r.toFixed(2)}</td>
                      <td className={`text-right font-mono ${s.total_r >= 0 ? "text-bull" : "text-bear"}`}>{s.total_r.toFixed(1)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            <div className="card overflow-x-auto">
              <div className="px-4 pt-4 text-xs uppercase tracking-wider text-slate-500">Recent simulated trades</div>
              <table className="table-base">
                <thead>
                  <tr><th>Date</th><th>Symbol</th><th>Dir</th><th className="text-right">Entry</th><th className="text-right">Exit</th><th>Outcome</th><th className="text-right">R</th></tr>
                </thead>
                <tbody>
                  {result.recent_trades.slice(0, 12).map((t, i) => (
                    <tr key={i}>
                      <td className="text-xs text-slate-500">{t.date}</td>
                      <td className="font-semibold text-slate-100">{t.symbol}</td>
                      <td><DirectionBadge direction={t.direction} /></td>
                      <td className="text-right font-mono">{usd(t.entry)}</td>
                      <td className="text-right font-mono">{usd(t.exit)}</td>
                      <td className="text-xs text-slate-400">{t.outcome}</td>
                      <td className={`text-right font-mono ${t.r >= 0 ? "text-bull" : "text-bear"}`}>{t.r.toFixed(2)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          <p className="text-[11px] text-slate-600 mt-3">{result.note}</p>
        </>
      )}

      {/* AI learning loop */}
      <h2 className="text-sm font-semibold uppercase tracking-wider text-slate-500 mt-10 mb-3">
        AI learning loop — probability calibration
      </h2>
      <div className="card p-5">
        {calib.data && (
          <>
            <p className="text-sm text-slate-400 mb-4">
              The AI compares its predicted win probability against actual paper-trade outcomes.
              {calib.data.active ? (
                <span className="text-bull"> Calibration is ACTIVE — new signals blend in your real results.</span>
              ) : (
                <span className="text-gold"> Needs {calib.data.min_samples_per_bucket}+ closed trades per bucket to activate
                ({calib.data.samples} closed so far). Keep paper trading — it learns as you go.</span>
              )}
            </p>
            <div className="grid grid-cols-2 sm:grid-cols-5 gap-3">
              {calib.data.buckets.map((b, i) => (
                <div key={i} className="bg-ink-850 border border-ink-800 rounded-lg p-3 text-center">
                  <div className="text-xs text-slate-500">{b.range[0]}–{b.range[1]}% predicted</div>
                  <div className="font-mono text-lg text-slate-200 mt-1">
                    {b.actual_win_rate !== null ? `${b.actual_win_rate}%` : "—"}
                  </div>
                  <div className="text-[11px] text-slate-500">actual · {b.count} trades</div>
                </div>
              ))}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function Param({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <label className="block">
      <span className="text-xs text-slate-500 block mb-1">{label}</span>
      {children}
    </label>
  );
}
