/* global React, Icon, EquityChart */
const { useState, useEffect, useMemo, useCallback } = React;
const DA = window.AURA_DATA;

const STATUS_OPTIONS = [
  { value: "", label: "All statuses" },
  { value: "connected", label: "Connected" },
  { value: "disconnected", label: "Disconnected" },
  { value: "error", label: "Error" },
];

const BOT_OPTIONS = [
  { value: "", label: "All bots" },
  { value: "true", label: "Bot active" },
  { value: "false", label: "Bot inactive" },
];

const selectStyle = {
  background: "var(--bg-2)", color: "var(--text-1)", border: "1px solid var(--line)",
  borderRadius: 4, fontSize: 12, padding: "6px 8px", cursor: "pointer",
};
const inputStyle = { ...selectStyle, cursor: "text" };

function stateColor(s) {
  return s === "active" ? "var(--green)" : s === "stale" ? "var(--amber)" : "var(--text-2)";
}

function AdminDashboard() {
  const [users, setUsers] = useState([]);
  const [stats, setStats] = useState(null);
  const [filters, setFilters] = useState({ user_id: "", status: "", bot_active: "", start: "", end: "" });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    window.api.adminUsers().then((u) => { if (u) setUsers(u); }).catch(() => {});
  }, []);

  const load = useCallback(() => {
    setLoading(true);
    setError(null);
    const payload = {
      user_id: filters.user_id || undefined,
      status: filters.status || undefined,
      bot_active: filters.bot_active === "" ? undefined : filters.bot_active,
      start: filters.start || undefined,
      // make `end` inclusive of the whole selected day
      end: filters.end ? `${filters.end}T23:59:59` : undefined,
    };
    window.api.adminStats(payload)
      .then((s) => { setStats(s); setLoading(false); })
      .catch((e) => { setError(e.message || "Failed to load admin stats"); setLoading(false); });
  }, [filters]);

  useEffect(() => { load(); }, [load]);

  const setFilter = (k, v) => setFilters((f) => ({ ...f, [k]: v }));
  const clearFilters = () => setFilters({ user_id: "", status: "", bot_active: "", start: "", end: "" });

  const totals = stats ? stats.totals : null;
  const accounts = stats ? stats.accounts : [];
  const equityCurve = useMemo(
    () => (stats && stats.platform_daily_pnl && stats.platform_daily_pnl.length ? stats.platform_daily_pnl : []),
    [stats]
  );

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Admin · Platform Overview</h1>
          <div className="page-subtitle">
            All users, accounts and bot KPIs · realized PnL from recorded trades
          </div>
        </div>
        <div style={{ marginLeft: "auto" }} className="row">
          <button className="btn ghost" onClick={load} disabled={loading}>
            <span>{Icon.refresh}</span>{loading ? "Loading…" : "Refresh"}
          </button>
        </div>
      </div>

      <div className="page-content col">
        {/* Filters */}
        <div className="panel" style={{ padding: "12px 14px" }}>
          <div className="row" style={{ flexWrap: "wrap", gap: 12, alignItems: "flex-end" }}>
            <FilterField label="User">
              <select style={selectStyle} value={filters.user_id} onChange={(e) => setFilter("user_id", e.target.value)}>
                <option value="">All users</option>
                {users.map((u) => (
                  <option key={u.id} value={u.id}>{u.name} ({u.account_count})</option>
                ))}
              </select>
            </FilterField>
            <FilterField label="Account status">
              <select style={selectStyle} value={filters.status} onChange={(e) => setFilter("status", e.target.value)}>
                {STATUS_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
              </select>
            </FilterField>
            <FilterField label="Bot">
              <select style={selectStyle} value={filters.bot_active} onChange={(e) => setFilter("bot_active", e.target.value)}>
                {BOT_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
              </select>
            </FilterField>
            <FilterField label="From">
              <input type="date" style={inputStyle} value={filters.start} onChange={(e) => setFilter("start", e.target.value)} />
            </FilterField>
            <FilterField label="To">
              <input type="date" style={inputStyle} value={filters.end} onChange={(e) => setFilter("end", e.target.value)} />
            </FilterField>
            <button className="btn ghost sm" onClick={clearFilters} style={{ marginLeft: "auto" }}>Clear</button>
          </div>
        </div>

        {error && (
          <div className="banner warn">
            <span style={{ width: 14, height: 14, color: "var(--amber)" }}>{Icon.alert}</span>
            <span>{error}</span>
          </div>
        )}

        {/* KPI summary */}
        {totals && (
          <div className="stat-grid" style={{ gridTemplateColumns: "repeat(5, 1fr)" }}>
            <div className="stat accent">
              <div className="stat-label">Total Balance {Icon.dollar}</div>
              <div className="stat-value"><span className="currency">$</span>{totals.total_balance.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>
              <div className="stat-meta"><span>Equity {DA.fmtUSD(totals.total_equity)}</span></div>
            </div>
            <div className={`stat ${totals.net_pnl >= 0 ? "pos" : "neg"}`}>
              <div className="stat-label">Net P&L (period) {Icon.activity}</div>
              <div className={`stat-value ${totals.net_pnl >= 0 ? "pos" : "neg"}`}>{DA.fmtSigned(totals.net_pnl)}</div>
              <div className="stat-meta"><span>Today {DA.fmtSigned(totals.today_pnl)}</span></div>
            </div>
            <div className="stat">
              <div className="stat-label">Win Rate {Icon.target}</div>
              <div className="stat-value">{totals.win_rate.toFixed(1)}<span className="currency" style={{ fontSize: 18 }}>%</span></div>
              <div className="stat-meta"><span>{totals.total_trades} trades</span></div>
            </div>
            <div className="stat">
              <div className="stat-label">Total Lots {Icon.zap}</div>
              <div className="stat-value">{totals.total_lots.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>
              <div className="stat-meta"><span>{totals.total_accounts} accounts · {totals.total_trades} trades</span></div>
            </div>
            <div className="stat">
              <div className="stat-label">Fleet {Icon.bot}</div>
              <div className="stat-value">{totals.active_bots}<span className="currency" style={{ fontSize: 14, marginLeft: 6 }}>/ {totals.total_accounts} active</span></div>
              <div className="stat-meta">
                <span>{totals.total_users} users</span>
                {totals.stale_bots > 0 && <span style={{ color: "var(--amber)" }}>{totals.stale_bots} stale</span>}
                {totals.circuit_broken > 0 && <span style={{ color: "var(--red)" }}>{totals.circuit_broken} CB tripped</span>}
              </div>
            </div>
          </div>
        )}

        {/* Platform equity curve */}
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title"><span className="live-dot"></span>Platform Realized P&L · Cumulative</div>
            <span className="pill neutral">{equityCurve.length} days</span>
          </div>
          <div style={{ padding: "10px 8px" }}>
            {equityCurve.length > 0 ? (
              <EquityChart data={equityCurve} height={260} />
            ) : (
              <div style={{ padding: "32px 14px", textAlign: "center", color: "var(--text-3)", fontFamily: "var(--font-mono)", fontSize: 11 }}>
                No closed trades in range
              </div>
            )}
          </div>
        </div>

        {/* Per-account table */}
        <div className="panel">
          <div className="panel-header">
            <div className="panel-title">Accounts · {accounts.length}</div>
          </div>
          <div style={{ overflowX: "auto" }}>
            <table className="tbl">
              <thead>
                <tr>
                  <th>Account</th>
                  <th>Owner</th>
                  <th>Bot</th>
                  <th className="num">Balance</th>
                  <th className="num">Equity</th>
                  <th className="num">Trades</th>
                  <th className="num">Win %</th>
                  <th className="num">PF</th>
                  <th className="num">Streak</th>
                  <th className="num">Net P&L</th>
                  <th className="num">Today</th>
                  <th className="num">Net %</th>
                  <th className="num">Max DD</th>
                  <th>Risk</th>
                  <th className="num">Lots</th>
                  <th className="num">Avg Lot</th>
                  <th>Sessions</th>
                </tr>
              </thead>
              <tbody>
                {accounts.length === 0 && (
                  <tr><td colSpan={17} style={{ padding: "28px 14px", textAlign: "center", color: "var(--text-3)", fontFamily: "var(--font-mono)", fontSize: 11 }}>
                    {loading ? "Loading…" : "No accounts match these filters"}
                  </td></tr>
                )}
                {accounts.map((a) => (
                  <tr key={a.account_id}>
                    <td>
                      <div style={{ fontWeight: 500 }}>{a.nickname || a.login}</div>
                      <div className="mono" style={{ fontSize: 10, color: "var(--text-3)" }}>#{a.login} · {a.server}</div>
                    </td>
                    <td>
                      <div>{a.owner_name}</div>
                      <div className="mono" style={{ fontSize: 10, color: "var(--text-3)" }}>{a.owner_email}</div>
                    </td>
                    <td>
                      <span className="pill" style={{ color: stateColor(a.bot_state), borderColor: "var(--line)" }}>
                        ● {a.bot_state}
                      </span>
                      <div className="mono" style={{ fontSize: 9, color: "var(--text-3)", marginTop: 2 }}>
                        {a.connection_status} · {a.strategy}
                      </div>
                    </td>
                    <td className="num">{DA.fmtUSD(a.balance)}</td>
                    <td className="num">{DA.fmtUSD(a.equity)}</td>
                    <td className="num">{a.total_trades}{a.open_positions > 0 && <span style={{ color: "var(--text-3)", fontSize: 10 }}> +{a.open_positions}</span>}</td>
                    <td className={`num ${a.win_rate >= 50 ? "pos" : "neg"}`}>{a.win_rate.toFixed(1)}%</td>
                    <td className={`num ${a.profit_factor >= 1 ? "pos" : "neg"}`}>{a.profit_factor.toFixed(2)}</td>
                    <td className={`num ${a.streak >= 0 ? "pos" : "neg"}`}>{a.streak > 0 ? `+${a.streak}W` : a.streak < 0 ? `${-a.streak}L` : "—"}</td>
                    <td className={`num ${a.net_pnl >= 0 ? "pos" : "neg"}`} style={{ fontWeight: 600 }}>{DA.fmtSigned(a.net_pnl)}</td>
                    <td className={`num ${a.today_pnl >= 0 ? "pos" : "neg"}`}>{DA.fmtSigned(a.today_pnl)}</td>
                    <td className={`num ${a.net_pnl_pct >= 0 ? "pos" : "neg"}`}>{DA.fmtPct(a.net_pnl_pct)}</td>
                    <td className="num neg">-{a.max_drawdown_pct.toFixed(2)}%</td>
                    <td>
                      <span style={{ color: a.circuit_broken ? "var(--red)" : "var(--green)", fontSize: 11 }}>
                        {a.circuit_broken ? "● CB tripped" : "● OK"}
                      </span>
                      <div className="mono" style={{ fontSize: 9, color: "var(--text-3)", marginTop: 2 }}>
                        streak {a.loss_streak}{a.max_loss_streak != null ? `/${a.max_loss_streak}` : ""}
                      </div>
                    </td>
                    <td className="num">{a.total_lots.toFixed(2)}</td>
                    <td className="num">{a.avg_lot.toFixed(3)}</td>
                    <td>
                      {a.sessions.length === 0
                        ? <span style={{ color: "var(--text-3)" }}>—</span>
                        : a.sessions.map((s) => <span key={s} className="pill neutral" style={{ fontSize: 9, marginRight: 3 }}>{s}</span>)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </>
  );
}

function FilterField({ label, children }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
      <span className="mono" style={{ fontSize: 9, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".12em" }}>{label}</span>
      {children}
    </div>
  );
}

window.AdminDashboard = AdminDashboard;
