import { useMemo } from 'react';
import { Link } from 'react-router-dom';
import { usePaperTrades } from '../../hooks/usePaperTrades';
import { tradePnl } from '../../lib/paperTrade';
import { formatPrice } from '../../lib/format';
import { Section } from '../ui/Section';
import { Callout } from '../ui/Callout';

function money(v: number): string {
  return `${v >= 0 ? '+' : '−'}$${Math.abs(v).toFixed(2)}`;
}
function fmtR(v: number | null): string {
  return v === null ? '—' : `${v > 0 ? '+' : ''}${v.toFixed(2)}R`;
}
function color(v: number | null): string {
  if (v === null) return 'text-gray-400';
  if (v > 0) return 'text-emerald-400';
  if (v < 0) return 'text-red-400';
  return 'text-gray-300';
}

// How the trade was closed — useful context on real trades at almost no cost.
function reasonMeta(reason: string | null): { label: string; cls: string } {
  switch (reason) {
    case 'stop': return { label: 'Stop', cls: 'text-red-400' };
    case 'trailing': return { label: 'Trail', cls: 'text-amber-400' };
    case 'target': return { label: 'Target', cls: 'text-emerald-400' };
    case 'time': return { label: 'Time', cls: 'text-gray-400' };
    case 'manual': return { label: 'Manual', cls: 'text-blue-300' };
    default: return { label: '—', cls: 'text-gray-500' };
  }
}

function Stat({ label, value, valueClass = 'text-gray-100', sub }: {
  label: string; value: string; valueClass?: string; sub?: string;
}) {
  return (
    <div className="glass p-4">
      <p className="section-index">{label}</p>
      <p className={`num mt-1.5 text-2xl font-semibold ${valueClass}`}>{value}</p>
      {sub && <p className="mt-1 text-xs text-gray-500">{sub}</p>}
    </div>
  );
}

export function MyTradesPanel() {
  const { data: closed, isLoading } = usePaperTrades('closed');

  const stats = useMemo(() => {
    const rows = (closed ?? []).map((t) => ({ t, p: tradePnl(t) }));
    const rs = rows.map((r) => r.p?.r).filter((r): r is number => r != null);
    const pnls = rows.map((r) => r.p?.pnl ?? 0);
    const alphas = rows.map((r) => r.t.alpha_usd).filter((a): a is number => a != null);
    const wins = pnls.filter((p) => p > 0).length;
    const losses = pnls.filter((p) => p < 0).length;
    const decided = wins + losses;
    return {
      total: rows.length,
      wins,
      losses,
      hitRate: decided ? (wins / decided) * 100 : null,
      avgR: rs.length ? rs.reduce((a, b) => a + b, 0) / rs.length : null,
      totalR: rs.length ? rs.reduce((a, b) => a + b, 0) : null,
      totalPnl: pnls.reduce((a, b) => a + b, 0),
      totalAlpha: alphas.length ? alphas.reduce((a, b) => a + b, 0) : null,
      rows,
    };
  }, [closed]);

  if (isLoading) return null;

  return (
    <Section title="My Trades" hint="your realized paper-trading results">
      {stats.total === 0 ? (
        <Callout variant="empty">
          No closed trades yet. Take setups as paper trades and they’ll resolve here when price hits
          the stop or target (or when you sell).
        </Callout>
      ) : (
        <div className="space-y-4">
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
            <Stat label="Hit Rate" value={stats.hitRate != null ? `${stats.hitRate.toFixed(1)}%` : '—'} sub={`${stats.wins}W / ${stats.losses}L`} />
            <Stat label="Expectancy" value={fmtR(stats.avgR)} valueClass={color(stats.avgR)} sub="avg R per closed trade" />
            <Stat label="Total R" value={fmtR(stats.totalR)} valueClass={color(stats.totalR)} sub={`${stats.total} closed`} />
            <Stat label="Total P&L" value={money(stats.totalPnl)} valueClass={color(stats.totalPnl)} sub="realized, all closed" />
            <Stat label="Alpha vs S&P 500" value={stats.totalAlpha != null ? money(stats.totalAlpha) : '—'} valueClass={color(stats.totalAlpha)} sub="realized vs buy-and-hold SPY" />
          </div>

          <div className="glass overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-white/[0.06] text-left text-xs uppercase tracking-wider text-gray-500">
                  <th className="px-4 py-2.5">Ticker</th>
                  <th className="px-4 py-2.5">Dir</th>
                  <th className="px-4 py-2.5 text-right">Entry</th>
                  <th className="px-4 py-2.5 text-right">Exit Px</th>
                  <th className="px-4 py-2.5 text-right">P&L</th>
                  <th className="px-4 py-2.5 text-right">R</th>
                  <th className="px-4 py-2.5 text-right">Alpha</th>
                  <th className="px-4 py-2.5">Reason</th>
                  <th className="px-4 py-2.5 text-right">Closed</th>
                </tr>
              </thead>
              <tbody>
                {stats.rows.map(({ t, p }) => (
                  <tr key={t.id} className="border-b border-white/[0.04] hover:bg-white/[0.03]">
                    <td className="px-4 py-2.5">
                      <Link to={`/ticker/${t.symbol}`} className="font-medium text-blue-300 hover:text-blue-200">{t.symbol}</Link>
                    </td>
                    <td className="px-4 py-2.5">
                      <span className={`num text-[10px] font-semibold uppercase ${t.direction === 'long' ? 'text-emerald-400' : 'text-red-400'}`}>{t.direction}</span>
                    </td>
                    <td className="num px-4 py-2.5 text-right text-gray-300">{formatPrice(t.entry_price)}</td>
                    <td className="num px-4 py-2.5 text-right text-gray-300">{t.close_price != null ? formatPrice(t.close_price) : '—'}</td>
                    <td className={`num px-4 py-2.5 text-right font-semibold ${p ? color(p.pnl) : 'text-gray-500'}`}>{p ? money(p.pnl) : '—'}</td>
                    <td className={`num px-4 py-2.5 text-right ${p?.r != null ? color(p.r) : 'text-gray-500'}`}>{p?.r != null ? fmtR(p.r) : '—'}</td>
                    <td className={`num px-4 py-2.5 text-right ${t.alpha_pct != null ? color(t.alpha_pct) : 'text-gray-500'}`} title="Return vs. S&P 500 over the holding period">{t.alpha_pct != null ? `${t.alpha_pct >= 0 ? '+' : ''}${t.alpha_pct.toFixed(1)}%` : '—'}</td>
                    <td className="px-4 py-2.5">
                      <span className={`num text-[10px] font-semibold uppercase tracking-wider ${reasonMeta(t.close_reason).cls}`} title="How the trade was closed">
                        {reasonMeta(t.close_reason).label}
                      </span>
                    </td>
                    <td className="num px-4 py-2.5 text-right text-gray-500">{t.closed_at ? new Date(t.closed_at).toLocaleDateString() : '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </Section>
  );
}
