"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 { dateTime, usd } from "@/lib/format";
import type { PaperTrade } from "@/lib/types";
import { useApi } from "@/lib/useApi";

function OptionCell({ t }: { t: PaperTrade }) {
  if (t.instrument !== "option" || !t.option_contract) {
    return <span className="text-slate-600 text-xs">shares only</span>;
  }
  const c = t.option_contract;
  const label = `${c.strike}${c.type === "call" ? "C" : "P"} ×${t.option_contracts ?? 0}`;
  return (
    <div className="text-xs">
      <div className="font-mono text-slate-200">{label}</div>
      <div className="text-slate-500">
        {c.expiry?.slice(5)} · {usd(t.option_last_premium ?? t.option_entry_premium ?? 0)}
      </div>
    </div>
  );
}

function OptPnl({ t }: { t: PaperTrade }) {
  if (t.instrument !== "option") return <span className="text-slate-600">—</span>;
  const v = t.option_pnl ?? 0;
  return <span className={`font-mono ${v >= 0 ? "text-bull" : "text-bear"}`}>{usd(v)}</span>;
}

export default function PaperTradesPage() {
  const { data, live, loading, refresh } = useApi(api.trades, 30_000);
  const [marking, setMarking] = useState(false);

  const trades = data ?? [];
  const open = trades.filter((t) => t.status === "open");
  const closed = trades.filter((t) => t.status === "closed");
  const realized = closed.reduce((a, t) => a + t.pnl, 0);
  const unrealized = open.reduce((a, t) => a + t.pnl, 0);
  const optionPnl = trades.reduce((a, t) => a + (t.option_pnl ?? 0), 0);

  const mark = async () => {
    setMarking(true);
    await api.markTrades();
    await refresh();
    setMarking(false);
  };

  const close = async (id: number) => {
    await api.closeTrade(id);
    await refresh();
  };

  return (
    <div>
      <PageHeader
        title="Paper Trades"
        subtitle="Simulated executions — shares validate direction, options track the real strategy"
        live={live}
        actions={
          <button
            onClick={mark}
            disabled={marking}
            className="text-xs px-4 py-2 rounded-lg bg-accent/15 border border-accent/40 text-accent hover:bg-accent/25 disabled:opacity-50"
          >
            {marking ? "Updating…" : "↻ Mark to Market"}
          </button>
        }
      />

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <StatCard label="Open / Closed" value={`${open.length} / ${closed.length}`} />
        <StatCard label="Unrealized P&L" value={usd(unrealized)} tone={unrealized >= 0 ? "up" : "down"} sub="Share basis" />
        <StatCard label="Realized P&L" value={usd(realized)} tone={realized >= 0 ? "up" : "down"} sub="Share basis" />
        <StatCard label="Option P&L" value={usd(optionPnl)} tone={optionPnl >= 0 ? "up" : "down"} sub="Premium basis, all trades" />
      </div>

      {loading && !data ? (
        <div className="text-slate-500 animate-pulse">Loading trades…</div>
      ) : (
        <>
          <Section title="Open positions">
            {open.length === 0 ? (
              <Empty text="No open paper trades. Open one from an approved signal." />
            ) : (
              <div className="card overflow-x-auto">
                <table className="table-base">
                  <thead>
                    <tr>
                      <th>Symbol</th><th>Dir</th>
                      <th>Option</th>
                      <th className="text-right">Entry</th>
                      <th className="text-right">Last</th>
                      <th className="text-right">Stop</th>
                      <th className="text-right">Target</th>
                      <th className="text-right">Share P&L</th>
                      <th className="text-right">Opt P&L</th>
                      <th className="text-right">Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    {open.map((t) => (
                      <tr key={t.id}>
                        <td>
                          <div className="font-semibold text-slate-100">{t.symbol}</div>
                          <div className="text-[11px] text-slate-500">{t.quantity} sh</div>
                        </td>
                        <td><DirectionBadge direction={t.direction} /></td>
                        <td><OptionCell t={t} /></td>
                        <td className="text-right font-mono">{usd(t.entry_price)}</td>
                        <td className="text-right font-mono">{usd(t.last_price)}</td>
                        <td className="text-right font-mono text-bear">{usd(t.stop_loss)}</td>
                        <td className="text-right font-mono text-bull">{usd(t.target)}</td>
                        <td className={`text-right font-mono ${t.pnl >= 0 ? "text-bull" : "text-bear"}`}>
                          {usd(t.pnl)}
                        </td>
                        <td className="text-right"><OptPnl t={t} /></td>
                        <td className="text-right">
                          <button
                            onClick={() => close(t.id)}
                            className="text-[11px] px-2 py-1 rounded border border-ink-600 text-slate-300 hover:bg-ink-700"
                          >
                            Close
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </Section>

          <Section title="Closed trades">
            {closed.length === 0 ? (
              <Empty text="No closed trades yet." />
            ) : (
              <div className="card overflow-x-auto">
                <table className="table-base">
                  <thead>
                    <tr>
                      <th>Symbol</th><th>Dir</th>
                      <th>Option</th>
                      <th className="text-right">Entry</th>
                      <th className="text-right">Exit</th>
                      <th>Reason</th>
                      <th className="text-right">Share P&L</th>
                      <th className="text-right">Opt P&L</th>
                      <th className="text-right">Closed</th>
                    </tr>
                  </thead>
                  <tbody>
                    {closed.map((t) => (
                      <tr key={t.id}>
                        <td>
                          <div className="font-semibold text-slate-100">{t.symbol}</div>
                          <div className="text-[11px] text-slate-500">{t.quantity} sh</div>
                        </td>
                        <td><DirectionBadge direction={t.direction} /></td>
                        <td><OptionCell t={t} /></td>
                        <td className="text-right font-mono">{usd(t.entry_price)}</td>
                        <td className="text-right font-mono">{t.exit_price ? usd(t.exit_price) : "—"}</td>
                        <td className="text-slate-400 text-xs">{t.exit_reason ?? "—"}</td>
                        <td className={`text-right font-mono ${t.pnl >= 0 ? "text-bull" : "text-bear"}`}>
                          {usd(t.pnl)}
                        </td>
                        <td className="text-right"><OptPnl t={t} /></td>
                        <td className="text-right text-xs text-slate-500">
                          {t.closed_at ? dateTime(t.closed_at) : "—"}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </Section>
        </>
      )}
    </div>
  );
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="mb-8">
      <h2 className="text-sm font-semibold uppercase tracking-wider text-slate-500 mb-3">{title}</h2>
      {children}
    </div>
  );
}

function Empty({ text }: { text: string }) {
  return <div className="card p-6 text-sm text-slate-500">{text}</div>;
}
