/* global React, AURA_DATA, Icon, Spark, EquityChart, BarChart, Donut */
const D3 = window.AURA_DATA;
const { useState, useEffect, useMemo } = React;

function ActiveTrades({ state }) {
  const { openTrades, setOpenTrades, activeAccount } = state;
  const unrealized = openTrades.reduce((a, b) => a + (b.pnl || 0), 0);

  const refresh = () => {
    if (activeAccount) window.api.openTrades(activeAccount.id).then(setOpenTrades).catch(() => {});
  };

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Active Trades</h1>
          <div className="page-subtitle">{openTrades.length} open · Unrealized {D3.fmtSigned(unrealized)}</div>
        </div>
        <div style={{ marginLeft: "auto" }} className="row">
          <button className="btn ghost" onClick={refresh}>{Icon.refresh}Refresh</button>
        </div>
      </div>
      <div className="page-content col">
        <div className="stat-grid">
          {[
            { l: "Open Positions", v: openTrades.length.toString() },
            { l: "Unrealized P&L", v: D3.fmtSigned(unrealized), c: unrealized >= 0 ? "pos" : "neg" },
            { l: "Total Volume", v: `${openTrades.reduce((a, b) => a + b.volume, 0).toFixed(2)} lots` },
            { l: "Positions", v: openTrades.length === 0 ? "No open trades" : `${openTrades.filter(t => t.pnl >= 0).length}W / ${openTrades.filter(t => t.pnl < 0).length}L` },
          ].map((m) => (
            <div className="stat" key={m.l}>
              <div className="stat-label">{m.l}</div>
              <div className={`stat-value ${m.c || ""}`}>{m.v}</div>
            </div>
          ))}
        </div>
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title"><span className="live-dot"></span>Live Positions</div>
          </div>
          {openTrades.length === 0 ? (
            <div style={{ padding: "48px 14px", textAlign: "center", color: "var(--text-3)", fontFamily: "var(--font-mono)", fontSize: 11 }}>
              No open positions — bot will show trades here when active
            </div>
          ) : (
            <table className="tbl">
              <thead>
                <tr><th>Ticket</th><th>Symbol</th><th>Dir</th><th className="num">Entry</th><th className="num">SL</th><th className="num">TP</th><th className="num">Vol</th><th className="num">P&L</th><th>Duration</th></tr>
              </thead>
              <tbody>
                {openTrades.map((p) => (
                  <tr key={p.ticket}>
                    <td style={{ color: "var(--text-3)" }}>#{p.ticket}</td>
                    <td className="sym">{p.symbol}</td>
                    <td><span className={`pill ${p.direction === "BUY" ? "buy" : "sell"}`}>{p.direction}</span></td>
                    <td className="num">{p.entry_price.toFixed(2)}</td>
                    <td className="num" style={{ color: "var(--red)" }}>{p.sl.toFixed(2)}</td>
                    <td className="num" style={{ color: "var(--green)" }}>{p.tp.toFixed(2)}</td>
                    <td className="num">{p.volume.toFixed(2)}</td>
                    <td className={`num ${(p.pnl || 0) >= 0 ? "pos" : "neg"}`} style={{ fontWeight: 600 }}>{D3.fmtSigned(p.pnl || 0)}</td>
                    <td className="mono" style={{ color: "var(--text-2)" }}>{D3.fmtDuration(p.open_time)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </>
  );
}

function TradeHistory({ state }) {
  const { activeAccount } = state;
  const [trades, setTrades] = useState([]);
  const [filter, setFilter] = useState("all");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!activeAccount) return;
    setLoading(true);
    window.api.tradeHistory(activeAccount.id, 200).then((t) => { setTrades(t || []); setLoading(false); }).catch(() => setLoading(false));
  }, [activeAccount]);

  const filtered = filter === "all" ? trades : trades.filter((t) => filter === "win" ? (t.pnl || 0) > 0 : (t.pnl || 0) <= 0);
  const totalPnL = filtered.reduce((a, b) => a + (b.pnl || 0), 0);
  const wins = trades.filter((t) => (t.pnl || 0) > 0).length;
  const losses = trades.filter((t) => (t.pnl || 0) <= 0).length;

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Trade History</h1>
          <div className="page-subtitle">{trades.length} trades · {wins}W / {losses}L</div>
        </div>
        <div style={{ marginLeft: "auto" }} className="row">
          <button className="btn ghost" onClick={() => { if (activeAccount) window.api.tradeHistory(activeAccount.id, 200).then((t) => setTrades(t || [])).catch(() => {}); }}>{Icon.refresh}Refresh</button>
        </div>
      </div>
      <div className="page-content col">
        <div className="row" style={{ gap: 8 }}>
          <div className="row" style={{ gap: 4, padding: 4, background: "var(--bg-1)", border: "1px solid var(--line)", borderRadius: "var(--radius)" }}>
            {[["all", "All"], ["win", "Wins"], ["loss", "Losses"]].map(([k, v]) => (
              <button key={k} className={`btn ${filter === k ? "" : "ghost"} sm`} onClick={() => setFilter(k)}>{v}</button>
            ))}
          </div>
          <div style={{ marginLeft: "auto", color: "var(--text-2)", fontFamily: "var(--font-mono)", fontSize: 11 }}>
            Total: <span className={totalPnL >= 0 ? "pos" : "neg"}>{D3.fmtSigned(totalPnL)}</span>
          </div>
        </div>
        <div className="panel">
          {loading ? (
            <div style={{ padding: 32, textAlign: "center", color: "var(--text-3)", fontFamily: "var(--font-mono)", fontSize: 11 }}>Loading…</div>
          ) : filtered.length === 0 ? (
            <div style={{ padding: 48, textAlign: "center", color: "var(--text-3)", fontFamily: "var(--font-mono)", fontSize: 11 }}>No trades found</div>
          ) : (
            <table className="tbl">
              <thead>
                <tr><th>Time</th><th>Ticket</th><th>Symbol</th><th>Dir</th><th className="num">Entry</th><th className="num">Exit</th><th className="num">Vol</th><th className="num">P&L</th><th>Reason</th></tr>
              </thead>
              <tbody>
                {filtered.map((t) => (
                  <tr key={t.ticket}>
                    <td className="mono" style={{ color: "var(--text-2)", whiteSpace: "nowrap" }}>{D3.fmtDateTime(t.close_time)}</td>
                    <td style={{ color: "var(--text-3)" }}>#{t.ticket}</td>
                    <td className="sym">{t.symbol}</td>
                    <td><span className={`pill ${t.direction === "BUY" ? "buy" : "sell"}`}>{t.direction}</span></td>
                    <td className="num">{t.entry_price.toFixed(2)}</td>
                    <td className="num">{t.exit_price != null ? t.exit_price.toFixed(2) : "—"}</td>
                    <td className="num">{t.volume.toFixed(2)}</td>
                    <td className={`num ${(t.pnl || 0) >= 0 ? "pos" : "neg"}`} style={{ fontWeight: 600 }}>{D3.fmtSigned(t.pnl || 0)}</td>
                    <td>
                      <span className="pill neutral" style={{ color: t.close_reason === "TP" ? "var(--green)" : t.close_reason === "SL" ? "var(--red)" : "var(--text-2)" }}>
                        {t.close_reason || "—"}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </>
  );
}

function SignalLog({ state }) {
  const { activeAccount } = state;
  const [signals, setSignals] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!activeAccount) return;
    setLoading(true);
    window.api.signals(activeAccount.id, 100).then((s) => { setSignals(s || []); setLoading(false); }).catch(() => setLoading(false));
  }, [activeAccount]);

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Signal Log</h1>
          <div className="page-subtitle">Bot reasoning for every cycle · last {signals.length} entries</div>
        </div>
      </div>
      <div className="page-content col">
        <div className="panel">
          {loading ? (
            <div style={{ padding: 32, textAlign: "center", color: "var(--text-3)", fontFamily: "var(--font-mono)", fontSize: 11 }}>Loading…</div>
          ) : signals.length === 0 ? (
            <div style={{ padding: 48, textAlign: "center", color: "var(--text-3)", fontFamily: "var(--font-mono)", fontSize: 11 }}>
              No signals yet — signals appear here once the bot is running
            </div>
          ) : (
            <div className="signal-feed">
              {signals.map((s, i) => (
                <div key={s.id || i} className="signal-item">
                  <span className="feed-time">{D3.fmtDateTime(s.created_at)}</span>
                  <span><span className={`pill ${s.direction === "BUY" ? "buy" : s.direction === "SELL" ? "sell" : "neutral"}`}>{s.direction}</span></span>
                  <span className="signal-reasoning">{s.reasoning}</span>
                  <span className="pill neutral" style={{ fontSize: 9, color: s.action === "opened" ? "var(--green)" : s.action === "skip_circuit_breaker" ? "var(--red)" : "var(--text-2)", whiteSpace: "nowrap" }}>
                    {s.action}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </>
  );
}

function Performance({ state }) {
  const { activeAccount } = state;
  const [perf, setPerf] = useState(null);
  const [days, setDays] = useState(30);

  useEffect(() => {
    if (!activeAccount) return;
    window.api.performance(activeAccount.id, days).then(setPerf).catch(() => {});
  }, [activeAccount, days]);

  const equity = useMemo(() => D3.generateEquityCurve(perf ? perf.equity_curve : []), [perf]);
  const bars = useMemo(() => D3.generateBars(perf ? perf.daily_pnl : []), [perf]);
  const wins = perf ? Math.round(perf.total_trades * perf.win_rate / 100) : 0;
  const losses = perf ? perf.total_trades - wins : 0;

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Performance & Analytics</h1>
          <div className="page-subtitle">Last {days} days · {perf ? perf.total_trades : "—"} trades</div>
        </div>
        <div style={{ marginLeft: "auto" }} className="row">
          {[7, 30, 90].map((d) => (
            <button key={d} className={`btn ${d === days ? "" : "ghost"} sm`} onClick={() => setDays(d)}>{d}D</button>
          ))}
        </div>
      </div>
      <div className="page-content col">
        <div className="stat-grid" style={{ gridTemplateColumns: "repeat(4, 1fr)" }}>
          {[
            { l: "Total Trades", v: perf ? perf.total_trades : "—" },
            { l: "Win Rate", v: perf ? `${perf.win_rate.toFixed(1)}%` : "—", c: "pos" },
            { l: "Net P&L", v: perf ? D3.fmtSigned(perf.net_pnl) : "—", c: perf && perf.net_pnl >= 0 ? "pos" : "neg" },
            { l: "Max DD", v: perf ? `-${perf.max_drawdown_pct.toFixed(2)}%` : "—", c: "neg" },
          ].map((m) => (
            <div className="stat" key={m.l} style={{ padding: "12px 14px" }}>
              <div className="stat-label" style={{ marginBottom: 6 }}>{m.l}</div>
              <div className={`stat-value ${m.c || ""}`} style={{ fontSize: 22 }}>{m.v}</div>
            </div>
          ))}
        </div>
        <div className="grid-2-1">
          <div className="panel">
            <div className="panel-header"><div className="panel-title">Equity Curve</div><span className="pill neutral">{days}D</span></div>
            <div style={{ padding: "10px 8px" }}><EquityChart data={equity} height={280} /></div>
          </div>
          <div className="panel">
            <div className="panel-header"><div className="panel-title">Win / Loss Distribution</div></div>
            <div style={{ padding: 24, display: "grid", placeItems: "center" }}>
              <Donut wins={wins || 1} losses={losses || 1} size={160} />
              <div style={{ display: "flex", gap: 18, marginTop: 18, fontFamily: "var(--font-mono)", fontSize: 11 }}>
                <div><span style={{ display: "inline-block", width: 8, height: 8, background: "var(--green)", borderRadius: 2, marginRight: 6 }}></span>Wins {wins}</div>
                <div><span style={{ display: "inline-block", width: 8, height: 8, background: "var(--line-2)", borderRadius: 2, marginRight: 6 }}></span>Losses {losses}</div>
              </div>
            </div>
          </div>
        </div>
        <div className="panel">
          <div className="panel-header"><div className="panel-title">Daily P&L</div></div>
          <div style={{ padding: 16 }}><BarChart data={bars} height={200} /></div>
        </div>
      </div>
    </>
  );
}

window.ActiveTrades = ActiveTrades;
window.TradeHistory = TradeHistory;
window.SignalLog = SignalLog;
window.Performance = Performance;
