// Trades page — full filterable history + modal.
const { Card, Pill, Copy, fmtTs, fmtNum } = window.UI;

// adapt one apiTrade to the rich row this page renders. Fields the
// backend doesn't yet ship (side, symbol, outbox_id, fills, fee) are
// filled with conservative defaults so the existing UI keeps working.
function adaptTradeRow(t, accountLabel) {
  const alt = parseFloat(t.alt_qty || '0') || 0;
  const crypto = parseFloat(t.crypto_qty || '0') || 0;
  const price = alt > 0 ? crypto / alt : 0;
  const symbol = (t.from && t.to) ? `${t.from}/${t.to}` : '';
  return {
    id: t.id,
    ts: t.ts_ms,
    account: accountLabel,
    from: t.from || '—',
    to: t.to || '—',
    qty: alt,
    price,
    fee: 0,
    state: t.state || 'PENDING',
    client_order_id: t.client_order_id || '',
    side: '', // round-trip swap (sell+buy) — single side label doesn't apply
    symbol,
    outbox_id: 0,
    fills: [],
  };
}

function PageTrades({ app }) {
  const [filters, setFilters] = React.useState({ account: 'all', state: 'all', side: 'all', symbol: '', from: '', to: '' });
  const [open, setOpen] = React.useState(null);

  // Resolve numeric account id for the current selection; backend takes
  // account_id only, so "all accounts" in the UI maps to the active acct.
  const acct = (app.accounts || []).find(a => a.id === app.account) || null;
  const accountID = acct && acct.accountID;

  const { data: rawTrades, error, loading, refresh } = window.API.useAPI(
    () => accountID ? window.API.get('/api/v1/trades', { account_id: accountID, limit: 500 }) : Promise.resolve([]),
    [accountID],
  );

  // No mock fallback: empty list = nothing yet.
  const source = (rawTrades && Array.isArray(rawTrades))
    ? rawTrades.map(t => adaptTradeRow(t, acct ? acct.id : ''))
    : [];

  const filtered = source.filter(t => {
    if (filters.account !== 'all' && t.account !== filters.account) return false;
    if (filters.state !== 'all' && t.state !== filters.state) return false;
    if (filters.side !== 'all' && (t.side || '') !== filters.side) return false;
    if (filters.symbol && !((t.symbol || '').toLowerCase()).includes(filters.symbol.toLowerCase())) return false;
    if (filters.from && t.ts < new Date(filters.from).getTime()) return false;
    if (filters.to && t.ts > new Date(filters.to).getTime()) return false;
    return true;
  });

  return (
    <div className="p-4 space-y-4">
      <div className="flex items-end justify-between">
        <div>
          <h1 className="text-[16px] font-medium text-ink-0">trade history</h1>
          <p className="mono text-[11px] text-ink-3 mt-0.5">
            {filtered.length} of {source.length} rows · click any row for fills breakdown · {' '}
            {loading && <span className="text-ink-3">loading…</span>}
            {error && <span className="text-neg-0">api error</span>}
            {!loading && !error && (source.length ? <span className="text-pos-0">live</span> : <span className="text-ink-3">no trades yet</span>)}
          </p>
        </div>
        <button onClick={refresh} className="px-2 h-7 mono text-[11px] uppercase tracking-[0.1em] border border-line-0 text-ink-2 hover:text-ink-0 hover:bg-bg-2">refresh</button>
      </div>

      {/* filter bar */}
      <Card padded={false}>
        <div className="px-3 py-2 grid grid-cols-6 gap-3 items-end">
          <Field label="account">
            <Select value={filters.account} onChange={v => setFilters(f => ({...f, account: v}))} options={[
              {v:'all', l:'all'}, ...(app.accounts || []).map(a => ({v: a.id, l: a.id}))
            ]}/>
          </Field>
          <Field label="state">
            <Select value={filters.state} onChange={v => setFilters(f => ({...f, state: v}))} options={[
              {v:'all',l:'all'},{v:'FILLED',l:'FILLED'},{v:'PARTIALLY_FILLED',l:'PARTIALLY_FILLED'},
              {v:'CANCELED',l:'CANCELED'},{v:'REJECTED',l:'REJECTED'}
            ]}/>
          </Field>
          <Field label="side">
            <Select value={filters.side} onChange={v => setFilters(f => ({...f, side: v}))} options={[
              {v:'all',l:'all'},{v:'BUY',l:'BUY'},{v:'SELL',l:'SELL'}
            ]}/>
          </Field>
          <Field label="symbol">
            <Input value={filters.symbol} onChange={v => setFilters(f => ({...f, symbol: v}))} placeholder="BTC/USDT" icon={Icon.Search}/>
          </Field>
          <Field label="from">
            <Input type="date" value={filters.from} onChange={v => setFilters(f => ({...f, from: v}))}/>
          </Field>
          <Field label="to">
            <Input type="date" value={filters.to} onChange={v => setFilters(f => ({...f, to: v}))}/>
          </Field>
        </div>
      </Card>

      <Card padded={false}>
        <div className="overflow-auto scrollbar max-h-[calc(100vh-250px)]">
          <table className="w-full text-[11.5px]">
            <thead className="text-ink-3 mono text-[10px] uppercase tracking-[0.1em] sticky top-0 bg-bg-1 z-10">
              <tr className="border-b border-line-0">
                <th className="text-left font-medium px-3 py-2">id</th>
                <th className="text-left font-medium px-3 py-2">time</th>
                <th className="text-left font-medium px-3 py-2">account</th>
                <th className="text-left font-medium px-3 py-2">from→to</th>
                <th className="text-right font-medium px-3 py-2">qty</th>
                <th className="text-right font-medium px-3 py-2">avg price</th>
                <th className="text-right font-medium px-3 py-2">fee</th>
                <th className="text-left font-medium px-3 py-2">state</th>
                <th className="text-left font-medium px-3 py-2">cid</th>
              </tr>
            </thead>
            <tbody className="mono">
              {filtered.map((t, i) => (
                <tr key={t.id} onClick={() => setOpen(t)}
                  className={`border-b border-line-0 cursor-pointer hover:bg-bg-2/60 ${i % 2 ? 'bg-bg-1' : 'bg-bg-1/50'}`}>
                  <td className="px-3 py-1.5 text-ink-3">#{t.id}</td>
                  <td className="px-3 py-1.5 text-ink-2">{fmtTs(t.ts)}</td>
                  <td className="px-3 py-1.5 text-ink-1">{t.account}</td>
                  <td className="px-3 py-1.5">
                    <span className="inline-flex items-center gap-1.5">
                      <span className="text-ink-0">{t.from}</span>
                      <Icon.ArrowRight size={11} className="text-ink-3"/>
                      <span className="text-ink-0">{t.to}</span>
                    </span>
                  </td>
                  <td className="px-3 py-1.5 text-right text-ink-0 num">{fmtNum(t.qty, 4)}</td>
                  <td className="px-3 py-1.5 text-right text-ink-0 num">{fmtNum(t.price, 2)}</td>
                  <td className="px-3 py-1.5 text-right text-ink-2 num">{fmtNum(t.fee, 4)}</td>
                  <td className="px-3 py-1.5">
                    <Pill tone={t.state === 'FILLED' ? 'pos' : t.state === 'PARTIALLY_FILLED' ? 'amb' : t.state === 'REJECTED' ? 'neg' : 'ink'}>
                      {t.state.replace('_',' ')}
                    </Pill>
                  </td>
                  <td className="px-3 py-1.5"><Copy text={t.client_order_id} display={t.client_order_id.slice(0, 18)+'…'}/></td>
                </tr>
              ))}
              {!filtered.length && (
                <tr><td colSpan={9} className="px-3 py-12 text-center text-ink-3 mono text-[11px]">no rows match filters</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </Card>

      {open && <TradeModal trade={open} onClose={() => setOpen(null)} />}
    </div>
  );
}

function Field({ label, children }) {
  return (
    <label className="block">
      <span className="text-[10px] uppercase tracking-[0.14em] text-ink-3 mono">{label}</span>
      <div className="mt-1">{children}</div>
    </label>
  );
}
function Select({ value, onChange, options }) {
  return (
    <div className="relative">
      <select value={value} onChange={e => onChange(e.target.value)}
        className="appearance-none w-full bg-bg-2 border border-line-1 mono text-[11.5px] h-7 pl-2 pr-7 text-ink-1 focus:border-line-2 outline-none">
        {options.map(o => <option key={o.v} value={o.v}>{o.l}</option>)}
      </select>
      <Icon.ChevronDown size={11} className="absolute right-2 top-2 text-ink-3 pointer-events-none"/>
    </div>
  );
}
function Input({ value, onChange, placeholder, type = 'text', icon: I }) {
  return (
    <div className="relative">
      {I && <I size={12} className="absolute left-2 top-2 text-ink-3"/>}
      <input type={type} value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder}
        className={`w-full bg-bg-2 border border-line-1 mono text-[11.5px] h-7 ${I ? 'pl-7' : 'pl-2'} pr-2 text-ink-1 focus:border-line-2 outline-none`}/>
    </div>
  );
}

function TradeModal({ trade, onClose }) {
  return (
    <>
      <div className="fixed inset-0 bg-black/50 z-40" onClick={onClose}/>
      <div className="fixed inset-0 z-50 grid place-items-center pointer-events-none p-6">
        <div className="bg-bg-1 border border-line-1 w-[640px] max-h-full pointer-events-auto flex flex-col">
          <header className="h-12 border-b border-line-0 flex items-center justify-between px-4">
            <div className="flex items-center gap-3">
              <h3 className="text-[12px] uppercase tracking-[0.14em] text-ink-1 font-medium">trade #{trade.id}</h3>
              <Pill tone={trade.state === 'FILLED' ? 'pos' : trade.state === 'PARTIALLY_FILLED' ? 'amb' : trade.state === 'REJECTED' ? 'neg' : 'ink'}>{trade.state.replace('_',' ')}</Pill>
            </div>
            <button onClick={onClose} className="p-1 text-ink-2 hover:text-ink-0"><Icon.X size={14}/></button>
          </header>
          <div className="p-4 space-y-4 overflow-auto scrollbar">
            <div className="grid grid-cols-4 gap-px bg-line-0">
              <KV3 k="time"     v={fmtTs(trade.ts)} />
              <KV3 k="account"  v={trade.account} />
              <KV3 k="symbol"   v={trade.symbol} />
              <KV3 k="side"     v={trade.side} />
              <KV3 k="from"     v={trade.from} />
              <KV3 k="to"       v={trade.to} />
              <KV3 k="qty"      v={fmtNum(trade.qty, 4)} />
              <KV3 k="avg price" v={fmtNum(trade.price, 2)} />
              <KV3 k="fee"      v={fmtNum(trade.fee, 4)} />
              <KV3 k="outbox id" v={`#${trade.outbox_id}`} />
              <KV3 k="cid"     v={<Copy text={trade.client_order_id} display={trade.client_order_id} className="text-ink-0"/>} colspan={2} />
            </div>

            {trade.fills.length > 0 && (
              <div>
                <div className="text-[10px] uppercase tracking-[0.14em] text-ink-3 mono mb-2">fills · {trade.fills.length}</div>
                <table className="w-full text-[11.5px] mono">
                  <thead className="text-ink-3 text-[10px] uppercase tracking-[0.1em]">
                    <tr className="border-b border-line-0">
                      <th className="text-left font-medium py-1.5">#</th>
                      <th className="text-right font-medium py-1.5">price</th>
                      <th className="text-right font-medium py-1.5">qty</th>
                      <th className="text-right font-medium py-1.5">commission</th>
                      <th className="text-left font-medium py-1.5 pl-3">role</th>
                    </tr>
                  </thead>
                  <tbody>
                    {trade.fills.map((f, i) => (
                      <tr key={i} className="border-b border-line-0">
                        <td className="py-1.5 text-ink-3">{i+1}</td>
                        <td className="py-1.5 text-right text-ink-0 num">{fmtNum(f.price, 2)}</td>
                        <td className="py-1.5 text-right text-ink-0 num">{fmtNum(f.qty, 4)}</td>
                        <td className="py-1.5 text-right text-ink-2 num">{fmtNum(f.commission, 4)}</td>
                        <td className="py-1.5 pl-3"><Pill tone={f.isMaker ? 'inf' : 'ink'}>{f.isMaker ? 'maker' : 'taker'}</Pill></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}

            <div className="flex justify-between items-center pt-2 border-t border-line-0">
              <span className="mono text-[10.5px] text-ink-3">originating outbox row #{trade.outbox_id}</span>
              <button className="mono text-[11px] text-inf-0 hover:text-ink-0 inline-flex items-center gap-1">
                view in replay at this timestamp <Icon.ArrowRight size={11}/>
              </button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

function KV3({ k, v, colspan = 1 }) {
  return (
    <div className="bg-bg-1 px-3 py-2" style={{ gridColumn: `span ${colspan}` }}>
      <div className="text-[9.5px] uppercase tracking-[0.14em] text-ink-3 mono">{k}</div>
      <div className="mono text-[12px] num mt-0.5 text-ink-0">{v}</div>
    </div>
  );
}

window.PageTrades = PageTrades;
