import { useMemo, useRef, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { getEquityCurve } from '../../api/paperTrades';
import { Section } from '../ui/Section';

const W = 760;
const H = 220;
const PAD = { top: 14, right: 84, bottom: 26, left: 56 };

function money(v: number): string {
  const sign = v > 0 ? '+' : v < 0 ? '−' : '';
  const abs = Math.abs(v);
  return `${sign}$${abs >= 10000 ? `${(abs / 1000).toFixed(1)}k` : abs.toFixed(0)}`;
}

/** Round tick steps to a clean 1/2/5 x 10^n ladder. */
function niceTicks(lo: number, hi: number, count = 4): number[] {
  const span = hi - lo || 1;
  const raw = span / count;
  const mag = 10 ** Math.floor(Math.log10(raw));
  const step = [1, 2, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? raw;
  const start = Math.ceil(lo / step) * step;
  const out: number[] = [];
  for (let v = start; v <= hi; v += step) out.push(v);
  return out;
}

/** Paper book vs the same dollars riding SPY — cumulative P&L since first trade. */
export function PerfChart() {
  const curve = useQuery({ queryKey: ['paper-trades', 'equity-curve'], queryFn: getEquityCurve });
  const [hover, setHover] = useState<number | null>(null);
  const svgRef = useRef<SVGSVGElement>(null);

  const data = curve.data ?? [];

  const geom = useMemo(() => {
    if (data.length < 2) return null;
    const values = data.flatMap((p) => [p.book_pnl, p.benchmark_pnl, 0]);
    const lo = Math.min(...values);
    const hi = Math.max(...values);
    const pad = (hi - lo) * 0.08 || 1;
    const yLo = lo - pad;
    const yHi = hi + pad;
    const plotW = W - PAD.left - PAD.right;
    const plotH = H - PAD.top - PAD.bottom;
    const px = (i: number) => PAD.left + (i / (data.length - 1)) * plotW;
    const py = (v: number) => PAD.top + plotH - ((v - yLo) / (yHi - yLo)) * plotH;
    const line = (key: 'book_pnl' | 'benchmark_pnl') =>
      data.map((p, i) => `${i === 0 ? 'M' : 'L'}${px(i).toFixed(1)},${py(p[key]).toFixed(1)}`).join(' ');
    // Month boundaries for the x axis.
    const xTicks: { i: number; label: string }[] = [];
    let lastMonth = '';
    data.forEach((p, i) => {
      const m = p.date.slice(0, 7);
      if (m !== lastMonth) {
        lastMonth = m;
        xTicks.push({ i, label: new Date(`${p.date}T00:00:00`).toLocaleDateString('en-US', { month: 'short' }) });
      }
    });
    if (xTicks.length > 8) {
      const keep = Math.ceil(xTicks.length / 8);
      for (let k = xTicks.length - 1; k >= 0; k--) if (k % keep !== 0) xTicks.splice(k, 1);
    }
    return { yLo, yHi, plotH, px, py, line, yTicks: niceTicks(yLo, yHi), xTicks };
  }, [data]);

  if (!geom) return null;
  const { px, py, line, yTicks, xTicks, plotH } = geom;

  const onMove = (e: React.MouseEvent<SVGSVGElement>) => {
    const rect = svgRef.current?.getBoundingClientRect();
    if (!rect) return;
    const x = ((e.clientX - rect.left) / rect.width) * W;
    const i = Math.round(((x - PAD.left) / (W - PAD.left - PAD.right)) * (data.length - 1));
    setHover(Math.max(0, Math.min(data.length - 1, i)));
  };

  const last = data.length - 1;
  const hb = hover !== null ? data[hover] : null;
  const fmtDate = (iso: string) =>
    new Date(`${iso}T00:00:00`).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });

  return (
    <Section title="Performance" hint="paper book vs the same dollars in SPY · cumulative P&L">
      <div className="glass p-5 pb-2">
        <div className="flex justify-end gap-4 text-xs text-gray-400">
          <span><i className="mr-1.5 inline-block h-2 w-2 rounded-full align-middle" style={{ background: 'var(--up)' }} /> Book</span>
          <span><i className="mr-1.5 inline-block h-2 w-2 rounded-full align-middle" style={{ background: 'var(--ink-3)' }} /> Same $ in SPY</span>
        </div>
        <svg
          ref={svgRef}
          viewBox={`0 0 ${W} ${H}`}
          className="mt-1 block h-auto w-full"
          onMouseMove={onMove}
          onMouseLeave={() => setHover(null)}
          role="img"
          aria-label={`Paper book cumulative P&L ${money(data[last].book_pnl)} versus ${money(data[last].benchmark_pnl)} for the same dollars in SPY`}
        >
          {yTicks.map((t) => (
            <g key={t}>
              <line x1={PAD.left} x2={W - PAD.right} y1={py(t)} y2={py(t)} stroke="var(--grid)" strokeWidth="1" />
              <text x={PAD.left - 8} y={py(t) + 3.5} textAnchor="end" className="num" fill="var(--ink-3)" fontSize="10">
                {money(t)}
              </text>
            </g>
          ))}
          {/* zero baseline slightly stronger when it's inside the plot */}
          <line x1={PAD.left} x2={W - PAD.right} y1={py(0)} y2={py(0)} stroke="var(--ink-3)" strokeWidth="1" opacity="0.5" />
          {xTicks.map(({ i, label }) => (
            <text key={`${label}-${i}`} x={px(i)} y={H - 6} textAnchor="middle" className="num" fill="var(--ink-3)" fontSize="10">
              {label}
            </text>
          ))}
          <path d={line('benchmark_pnl')} fill="none" stroke="var(--ink-3)" strokeWidth="2" strokeLinejoin="round" />
          <path d={line('book_pnl')} fill="none" stroke="var(--up)" strokeWidth="2" strokeLinejoin="round" />
          {hover !== null && (
            <g>
              <line x1={px(hover)} x2={px(hover)} y1={PAD.top} y2={PAD.top + plotH} stroke="var(--ink-3)" strokeWidth="1" />
              <circle cx={px(hover)} cy={py(data[hover].book_pnl)} r="4.5" fill="var(--up)" stroke="var(--surface)" strokeWidth="2" />
              <circle cx={px(hover)} cy={py(data[hover].benchmark_pnl)} r="4.5" fill="var(--ink-3)" stroke="var(--surface)" strokeWidth="2" />
            </g>
          )}
          <circle cx={px(last)} cy={py(data[last].book_pnl)} r="4" fill="var(--up)" stroke="var(--surface)" strokeWidth="2" />
          <circle cx={px(last)} cy={py(data[last].benchmark_pnl)} r="4" fill="var(--ink-3)" stroke="var(--surface)" strokeWidth="2" />
          <text x={px(last) + 10} y={py(data[last].book_pnl) + 4} className="num" fill="var(--ink)" fontSize="11" fontWeight="600">
            {money(data[last].book_pnl)}
          </text>
          <text x={px(last) + 10} y={py(data[last].benchmark_pnl) + 4} className="num" fill="var(--ink-2)" fontSize="11">
            {money(data[last].benchmark_pnl)}
          </text>
        </svg>
        <p className="num px-1 pb-1 pt-1.5 text-[11px] text-gray-500" aria-live="polite">
          {hb
            ? <>{fmtDate(hb.date)} — book <b className="text-gray-200">{money(hb.book_pnl)}</b> · SPY <b className="text-gray-200">{money(hb.benchmark_pnl)}</b></>
            : <>hover for daily values · realized + mark-to-market, since first paper trade</>}
        </p>
      </div>
    </Section>
  );
}
