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

const W = 1040;
const H = 260;
const PAD = { top: 16, right: 92, bottom: 28, left: 60 };

const COLORS = {
  shadow: 'var(--up)',
  manual: 'var(--accent, #7aa2f7)',
  spy: 'var(--ink-3)',
} as const;

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;
}

/** R-multiple stats read straight across; currency P&L does not, because the
 *  books size differently. Kept adjacent so the comparison is hard to misread. */
function StatCell({ label, stats, color }: { label: string; stats?: BookStats; color: string }) {
  if (!stats || stats.trades === 0) {
    return (
      <div className="min-w-[7rem]">
        <div className="flex items-center gap-1.5 text-xs text-gray-400">
          <i className="inline-block h-2 w-2 rounded-full" style={{ background: color }} />
          {label}
        </div>
        <div className="num mt-1 text-sm text-gray-500">no trades yet</div>
      </div>
    );
  }
  return (
    <div className="min-w-[7rem]">
      <div className="flex items-center gap-1.5 text-xs text-gray-400">
        <i className="inline-block h-2 w-2 rounded-full" style={{ background: color }} />
        {label}
      </div>
      <div className="num mt-1 text-lg font-semibold text-gray-100">
        {stats.total_r > 0 ? '+' : ''}
        {stats.total_r.toFixed(2)}R
      </div>
      <div className="num text-[11px] leading-relaxed text-gray-500">
        {stats.trades} trades · {stats.win_rate ?? '—'}% win
        <br />
        avg {stats.avg_r === null ? '—' : `${stats.avg_r > 0 ? '+' : ''}${stats.avg_r.toFixed(2)}R`} · {money(stats.pnl)}
      </div>
    </div>
  );
}

/** Shadow book (the strategy, traded automatically) vs the discretionary book
 *  vs SPY. Both books share an exit policy, so the only difference is which
 *  qualified setups get taken. */
export function PerfChart() {
  const perf = useQuery({ queryKey: ['paper-trades', 'performance'], queryFn: getPerformance });
  const [hover, setHover] = useState<number | null>(null);
  const svgRef = useRef<SVGSVGElement>(null);

  const data = perf.data?.series ?? [];
  const stats = perf.data?.stats ?? {};
  const startDate = perf.data?.start_date ?? null;

  const geom = useMemo(() => {
    if (data.length < 2) return null;
    const values = data.flatMap((p) => [p.manual_pnl, p.shadow_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: 'manual_pnl' | 'shadow_pnl') =>
      data.map((p, i) => `${i === 0 ? 'M' : 'L'}${px(i).toFixed(1)},${py(p[key]).toFixed(1)}`).join(' ');

    // SPY is a percentage reference, so it rides its own scale pinned to the
    // same zero line — otherwise a flat book would squash it out of view.
    const spyLo = Math.min(...data.map((p) => p.spy_pct), 0);
    const spyHi = Math.max(...data.map((p) => p.spy_pct), 0);
    const spySpan = Math.max(Math.abs(spyLo), Math.abs(spyHi)) || 1;
    const bookSpan = Math.max(Math.abs(yLo), Math.abs(yHi)) || 1;
    const spyY = (v: number) => py((v / spySpan) * bookSpan);
    const spyLine = data
      .map((p, i) => `${i === 0 ? 'M' : 'L'}${px(i).toFixed(1)},${spyY(p.spy_pct).toFixed(1)}`)
      .join(' ');

    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 > 10) {
      const keep = Math.ceil(xTicks.length / 10);
      for (let k = xTicks.length - 1; k >= 0; k--) if (k % keep !== 0) xTicks.splice(k, 1);
    }
    return { yLo, yHi, plotH, px, py, line, spyLine, spyY, yTicks: niceTicks(yLo, yHi), xTicks };
  }, [data]);

  if (!geom) {
    return (
      <Section title="Performance" hint="shadow book vs your picks vs SPY">
        <div className="glass p-5 text-sm text-gray-500">
          No trades in the selected window yet
          {startDate ? ` (since ${startDate})` : ''}. The shadow book starts recording once enabled.
        </div>
      </Section>
    );
  }
  const { px, py, line, spyLine, spyY, 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={`shadow book vs your picks vs SPY${startDate ? ` · since ${startDate}` : ''}`}
    >
      <div className="glass p-5 pb-2">
        <div className="mb-3 flex flex-wrap items-start justify-between gap-x-8 gap-y-3">
          <div className="flex flex-wrap gap-x-8 gap-y-3">
            <StatCell label="Shadow (strategy)" stats={stats.shadow} color={COLORS.shadow} />
            <StatCell label="Your picks" stats={stats.manual} color={COLORS.manual} />
            <div className="min-w-[7rem]">
              <div className="flex items-center gap-1.5 text-xs text-gray-400">
                <i className="inline-block h-2 w-2 rounded-full" style={{ background: COLORS.spy }} />
                SPY
              </div>
              <div className="num mt-1 text-lg font-semibold text-gray-300">
                {(stats.spy?.pct ?? 0) > 0 ? '+' : ''}
                {(stats.spy?.pct ?? 0).toFixed(1)}%
              </div>
              <div className="num text-[11px] text-gray-500">buy &amp; hold</div>
            </div>
          </div>
          <p className="max-w-[22rem] text-[11px] leading-relaxed text-gray-500">
            Books share the same exit, so the difference is <b className="text-gray-400">selection</b>.
            Compare on <b className="text-gray-400">R</b>, not $ — sizing differs. Expect months of
            noise before a gap means anything.
          </p>
        </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={`Shadow book ${money(data[last].shadow_pnl)}, your picks ${money(
            data[last].manual_pnl,
          )}, SPY ${(data[last].spy_pct ?? 0).toFixed(1)} percent`}
        >
          {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>
          ))}
          <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={spyLine} fill="none" stroke={COLORS.spy} strokeWidth="1.5" strokeDasharray="4 3" strokeLinejoin="round" />
          <path d={line('manual_pnl')} fill="none" stroke={COLORS.manual} strokeWidth="2" strokeLinejoin="round" />
          <path d={line('shadow_pnl')} fill="none" stroke={COLORS.shadow} 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].shadow_pnl)} r="4.5" fill={COLORS.shadow} stroke="var(--surface)" strokeWidth="2" />
              <circle cx={px(hover)} cy={py(data[hover].manual_pnl)} r="4.5" fill={COLORS.manual} stroke="var(--surface)" strokeWidth="2" />
              <circle cx={px(hover)} cy={spyY(data[hover].spy_pct)} r="4" fill={COLORS.spy} stroke="var(--surface)" strokeWidth="2" />
            </g>
          )}
          <text x={px(last) + 10} y={py(data[last].shadow_pnl) + 4} className="num" fill="var(--ink)" fontSize="11" fontWeight="600">
            {money(data[last].shadow_pnl)}
          </text>
          <text x={px(last) + 10} y={py(data[last].manual_pnl) + 4} className="num" fill="var(--ink-2)" fontSize="11">
            {money(data[last].manual_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)} — shadow <b className="text-gray-200">{money(hb.shadow_pnl)}</b> · yours{' '}
              <b className="text-gray-200">{money(hb.manual_pnl)}</b> · SPY{' '}
              <b className="text-gray-200">{hb.spy_pct.toFixed(1)}%</b>
            </>
          ) : (
            <>hover for daily values · realized + mark-to-market{startDate ? ` · window starts ${startDate}` : ''}</>
          )}
        </p>
      </div>
    </Section>
  );
}
