import React, { useEffect, useState } from 'react'
import { api } from '../services/api'
import './AdminDashboard.css'

export default function AdminDashboard() {
  const [dashboardData, setDashboardData] = useState(null)
  const [orderStats, setOrderStats] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  const loadData = async () => {
    try {
      if (!dashboardData) setLoading(true)
      const [dashboardRes, statsRes] = await Promise.all([
        api.getAdminDashboard(),
        api.getAdminOverallTradeStats(7).catch(() => null)
      ])
      setDashboardData(dashboardRes)
      setOrderStats(statsRes)
      setError(null)
    } catch (err) {
      setError(err?.message)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadData()
    const timer = setInterval(loadData, 30000)
    return () => clearInterval(timer)
  }, [])

  if (loading && !dashboardData) return <div className="loading">加载中...</div>
  if (error) return <div className="error">加载失败: {error}</div>
  if (!dashboardData) return null

  const summary = dashboardData.summary || {}

  return (
    <div className="admin-dashboard">
      <div className="dashboard-header">
        <h2>全局交易监控看板</h2>
        <button className="refresh-btn" onClick={loadData}>刷新</button>
      </div>

      <div className="summary-cards">
        <div className="card">
          <div className="card-title">总资产 (USDT)</div>
          <div className="card-value">
            {(summary.total_assets_usdt ?? 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
          </div>
          <div className="card-desc">各账号 account_snapshots 快照汇总，不调币安。由定时任务 sync_binance_orders.py 每 3 小时同步时写入；若为 0 请先跑一次该脚本</div>
        </div>
        <div className="card">
          <div className="card-title">总盈亏 (USDT)</div>
          <div className={`card-value ${(summary.total_pnl_usdt ?? 0) >= 0 ? 'profit' : 'loss'}`}>
            {(summary.total_pnl_usdt ?? 0) >= 0 ? '+' : ''}
            {(summary.total_pnl_usdt ?? 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
          </div>
          <div className="card-desc">最近 7 天聚合已实现盈亏</div>
        </div>
        <div className="card">
          <div className="card-title">活跃账户数</div>
          <div className="card-value">{summary.active_accounts ?? 0} / {summary.total_accounts ?? 0}</div>
        </div>
      </div>

      <div className="dashboard-card stats-card">
        <div className="stats-card-header">
          <h3>整体订单统计（最近 7 天）</h3>
        </div>
        {orderStats ? (
          <>
            {orderStats.summary && (
              <div className="stats-section">
                <h4>汇总</h4>
                <p>
                  笔数 <strong>{orderStats.summary.trade_count ?? 0}</strong>
                  ，盈 <strong>{orderStats.summary.win_count ?? 0}</strong> / 亏 <strong>{orderStats.summary.loss_count ?? 0}</strong>
                  ，净盈亏 <span className={Number(orderStats.summary.net_pnl) >= 0 ? 'positive' : 'negative'}>
                    {Number(orderStats.summary.net_pnl) >= 0 ? '+' : ''}{Number(orderStats.summary.net_pnl).toFixed(2)} USDT
                  </span>
                </p>
              </div>
            )}
            <div className="stats-section">
              <h4>按交易对：净盈亏、胜率</h4>
              {orderStats.by_symbol?.length > 0 ? (
                <div className="stats-table-wrap">
                  <table className="stats-table">
                    <thead>
                      <tr>
                        <th>交易对</th>
                        <th>笔数</th>
                        <th>胜率%</th>
                        <th>净盈亏(USDT)</th>
                      </tr>
                    </thead>
                    <tbody>
                      {orderStats.by_symbol.map((row) => (
                        <tr key={row.symbol}>
                          <td className="stats-symbol">{row.symbol}</td>
                          <td>{row.trade_count}</td>
                          <td>{row.win_rate_pct}</td>
                          <td className={Number(row.net_pnl) >= 0 ? 'positive' : 'negative'}>
                            {Number(row.net_pnl) >= 0 ? '+' : ''}{Number(row.net_pnl).toFixed(2)}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <p className="stats-empty">暂无按交易对统计（需先运行 scripts/aggregate_trade_stats.py 或依赖定时任务）</p>
              )}
            </div>
            <div className="stats-section">
              <h4>按小时：净盈亏（0–23 时，北京时间）</h4>
              {orderStats.hourly_agg?.length > 0 ? (
                <div className="stats-table-wrap hourly-table">
                  <table className="stats-table">
                    <thead>
                      <tr>
                        <th>小时</th>
                        <th>笔数</th>
                        <th>净盈亏(USDT)</th>
                      </tr>
                    </thead>
                    <tbody>
                      {orderStats.hourly_agg.map((row) => (
                        <tr key={row.hour}>
                          <td>{row.hour}:00</td>
                          <td>{row.trade_count}</td>
                          <td className={Number(row.net_pnl) >= 0 ? 'positive' : 'negative'}>
                            {Number(row.net_pnl) >= 0 ? '+' : ''}{Number(row.net_pnl).toFixed(2)}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <p className="stats-empty">暂无按小时统计</p>
              )}
            </div>
            {orderStats.suggestions && (orderStats.suggestions.blacklist?.length > 0 || orderStats.suggestions.whitelist?.length > 0) && (
              <div className="stats-section suggestions-section">
                <h4>策略建议（仅供参考）</h4>
                {orderStats.suggestions.blacklist?.length > 0 && (
                  <div className="suggestion-block blacklist">
                    <strong>建议降权/观察：</strong>
                    <ul>
                      {orderStats.suggestions.blacklist.map((item) => (
                        <li key={item.symbol}>
                          <span className="suggestion-symbol">{item.symbol}</span>
                          笔数 {item.trade_count}，净盈亏 {item.net_pnl} USDT，胜率 {item.win_rate_pct}%
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
                {orderStats.suggestions.whitelist?.length > 0 && (
                  <div className="suggestion-block whitelist">
                    <strong>可优先考虑：</strong>
                    <ul>
                      {orderStats.suggestions.whitelist.map((item) => (
                        <li key={item.symbol}>
                          <span className="suggestion-symbol">{item.symbol}</span>
                          笔数 {item.trade_count}，净盈亏 +{item.net_pnl} USDT，胜率 {item.win_rate_pct}%
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
              </div>
            )}
          </>
        ) : (
          <p className="stats-empty">加载统计中…（若长期无数据，请先运行 scripts/aggregate_trade_stats.py 或依赖定时任务更新）</p>
        )}
      </div>
    </div>
  )
}
