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

function downloadJson(data, filename) {
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  a.click()
  URL.revokeObjectURL(url)
}

export default function DataManagement() {
  const [accounts, setAccounts] = useState([])

  // DB 交易
  const [dbAccountId, setDbAccountId] = useState('')
  const [dbDate, setDbDate] = useState(() => new Date().toISOString().slice(0, 10))
  const [dbTimeFilter, setDbTimeFilter] = useState('created')
  const [dbReconciledOnly, setDbReconciledOnly] = useState(false)
  const [dbSymbol, setDbSymbol] = useState('')
  const [dbLoading, setDbLoading] = useState(false)
  const [dbResult, setDbResult] = useState(null)
  const [dbError, setDbError] = useState('')

  // 币安拉取
  const [bnAccountId, setBnAccountId] = useState('')
  const [bnSymbols, setBnSymbols] = useState('')
  const [bnDataType, setBnDataType] = useState('trades')
  const [bnDays, setBnDays] = useState(7)
  const [bnLoading, setBnLoading] = useState(false)
  const [bnResult, setBnResult] = useState(null)
  const [bnError, setBnError] = useState('')

  const activeAccounts = accounts.filter((a) => (a.status || 'active').toLowerCase() === 'active')

  useEffect(() => {
    api.getDataManagementAccounts().then((r) => {
      const list = Array.isArray(r?.accounts) ? r.accounts : (Array.isArray(r) ? r : [])
      setAccounts(list)
      const active = list.filter((a) => (a.status || 'active').toLowerCase() === 'active')
      const first = active[0] || list[0]
      if (!dbAccountId && first) setDbAccountId(String(first.id))
      if (!bnAccountId && first) setBnAccountId(String(first.id))
    }).catch(() => {})
  }, [])

  const queryDbTrades = async () => {
    const aid = parseInt(dbAccountId, 10)
    if (!aid) {
      setDbError('请选择账号')
      return
    }
    setDbLoading(true)
    setDbError('')
    setDbResult(null)
    try {
      const params = { account_id: aid, time_filter: dbTimeFilter }
      if (dbDate) params.date = dbDate
      if (dbReconciledOnly) params.reconciled_only = 'true'
      if (dbSymbol && dbSymbol.trim()) params.symbol = dbSymbol.trim()
      const res = await api.getDataManagementDbTrades(params)
      setDbResult(res)
    } catch (e) {
      setDbError(e?.message || '查询失败')
    } finally {
      setDbLoading(false)
    }
  }

  const fetchBinance = async () => {
    const aid = parseInt(bnAccountId, 10)
    if (!aid) {
      setBnError('请选择账号')
      return
    }
    setBnLoading(true)
    setBnError('')
    setBnResult(null)
    try {
      const params = { account_id: aid, data_type: bnDataType, days: bnDays }
      if (bnSymbols.trim()) params.symbols = bnSymbols.trim()
      const res = await api.postDataManagementFetchBinance(params)
      setBnResult(res)
    } catch (e) {
      setBnError(e?.message || '查询失败')
    } finally {
      setBnLoading(false)
    }
  }

  const exportDb = () => {
    if (!dbResult?.trades) return
    const filename = `db_trades_${dbAccountId}_${dbDate || 'today'}_${dbTimeFilter}.json`
    downloadJson(dbResult, filename)
  }

  const exportBinance = () => {
    const items = bnResult?.data || bnResult?.items
    if (!items) return
    const filename = `binance_${bnResult.data_type}_${bnAccountId}_${new Date().toISOString().slice(0, 10)}.json`
    const payload = {
      meta: { total: bnResult.total, data_type: bnResult.data_type, symbols_queried: bnResult.symbols_queried, export_time: new Date().toISOString() },
      stats: bnResult.stats || {},
      data: items,
    }
    downloadJson(payload, filename)
  }

  const bnData = bnResult?.data || bnResult?.items || []
  const bnStats = bnResult?.stats || {}
  const isTrades = bnResult?.data_type === 'trades'

  const today = new Date().toISOString().slice(0, 10)

  return (
    <div className="data-management">
      <h2>数据管理</h2>
      <p className="dm-subtitle">查询 DB 交易记录、从币安拉取订单/成交，支持导出 JSON 做策略分析与对账。</p>

      {/* 1. 查询 DB 交易 */}
      <section className="dm-section">
        <h3>查询 DB 交易</h3>
        <div className="dm-controls">
          <label>
            账号
            <select value={dbAccountId} onChange={(e) => setDbAccountId(e.target.value)}>
              <option value="">请选择</option>
              {activeAccounts.map((a) => (
                <option key={a.id} value={a.id}>{a.name || `账号${a.id}`}</option>
              ))}
            </select>
          </label>
          <label>
            日期 (YYYY-MM-DD)
            <input type="date" value={dbDate} onChange={(e) => setDbDate(e.target.value)} max={today} placeholder="留空=今天" />
          </label>
          <label>
            时间筛选
            <select value={dbTimeFilter} onChange={(e) => setDbTimeFilter(e.target.value)}>
              <option value="created">按创建时间</option>
              <option value="entry">按开仓时间</option>
              <option value="exit">按平仓时间</option>
            </select>
          </label>
          <label className="dm-check">
            <input type="checkbox" checked={dbReconciledOnly} onChange={(e) => setDbReconciledOnly(e.target.checked)} />
            仅可对账（有 entry/exit orderId）
          </label>
          <label>
            交易对
            <input type="text" value={dbSymbol} onChange={(e) => setDbSymbol(e.target.value)} placeholder="留空=全部" />
          </label>
          <button className="btn btn-primary" onClick={queryDbTrades} disabled={dbLoading}>
            {dbLoading ? '查询中...' : '查询'}
          </button>
        </div>
        {dbError && <div className="dm-error">{dbError}</div>}
        {dbResult && (
          <div className="dm-result">
            <div className="dm-result-meta">
              共 {dbResult.total} 条
              <button className="btn btn-sm" onClick={exportDb}>导出 JSON</button>
            </div>
            <div className="dm-table-wrap">
              <table className="dm-table">
                <thead>
                  <tr>
                    <th>ID</th>
                    <th>交易对</th>
                    <th>状态</th>
                    <th>入场价</th>
                    <th>出场价</th>
                    <th>盈亏</th>
                    <th>开仓时间</th>
                    <th>平仓时间</th>
                  </tr>
                </thead>
                <tbody>
                  {(dbResult.trades || []).slice(0, 100).map((t) => (
                    <tr key={t.id}>
                      <td>{t.id}</td>
                      <td>{t.symbol}</td>
                      <td>{t.status}</td>
                      <td>{t.entry_price}</td>
                      <td>{t.exit_price}</td>
                      <td>{t.realized_pnl}</td>
                      <td>{t.entry_time || '-'}</td>
                      <td>{t.exit_time || '-'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {(dbResult.trades?.length || 0) > 100 && (
                <div className="dm-more">仅显示前 100 条，共 {dbResult.total} 条。导出可获取全部。</div>
              )}
            </div>
          </div>
        )}
      </section>

      {/* 2. 币安订单/成交（从 DB 查询，由定时任务 scripts/sync_binance_orders.py 每 3 小时同步，存在一定延时） */}
      <section className="dm-section">
        <h3>币安订单/成交查询</h3>
        <div className="dm-controls">
          <label>
            账号
            <select value={bnAccountId} onChange={(e) => setBnAccountId(e.target.value)}>
              <option value="">请选择</option>
              {activeAccounts.map((a) => (
                <option key={a.id} value={a.id}>{a.name || `账号${a.id}`}</option>
              ))}
            </select>
          </label>
          <label>
            交易对
            <input type="text" value={bnSymbols} onChange={(e) => setBnSymbols(e.target.value)} placeholder="留空=全部，或逗号分隔如 ASTERUSDT,FILUSDT" style={{ minWidth: 280 }} />
          </label>
          <label>
            数据类型
            <select value={bnDataType} onChange={(e) => setBnDataType(e.target.value)}>
              <option value="trades">成交记录</option>
              <option value="orders">订单列表</option>
            </select>
          </label>
          <label>
            时间范围
            <select value={bnDays} onChange={(e) => setBnDays(Number(e.target.value))}>
              <option value={0}>当天</option>
              {[1, 2, 3, 5, 7].map((d) => (
                <option key={d} value={d}>{d} 天</option>
              ))}
            </select>
          </label>
          <button className="btn btn-primary" onClick={fetchBinance} disabled={bnLoading}>
            {bnLoading ? '查询中...' : '查询'}
          </button>
        </div>
        {bnError && <div className="dm-error">{bnError}</div>}
        {bnResult && (
          <div className="dm-result">
            <div className="dm-result-meta">
              共 {bnResult.total} 条 · 查询 {bnResult.symbols_queried ?? '-'} 个交易对
              {bnResult.source === 'db' && <span className="dm-source-tag" title="定时任务每 3 小时的第 0 分钟同步，存在一定延时">来自 DB（定时同步）</span>}
              <button className="btn btn-sm" onClick={exportBinance}>导出 JSON（含统计与全部字段）</button>
            </div>

            {Object.keys(bnStats).length > 0 && (
              <div className="dm-stats">
                <h4>统计数据</h4>
                <div className="dm-stats-grid">
                  {isTrades && bnStats.total_realized_pnl !== undefined && (
                    <>
                      <div className="dm-stat-item">
                        <span className="dm-stat-label">总已实现盈亏</span>
                        <span className={bnStats.total_realized_pnl >= 0 ? 'dm-stat-profit' : 'dm-stat-loss'}>{bnStats.total_realized_pnl}</span>
                      </div>
                      <div className="dm-stat-item">
                        <span className="dm-stat-label">总手续费</span>
                        <span>{bnStats.total_commission}</span>
                      </div>
                      <div className="dm-stat-item">
                        <span className="dm-stat-label">净盈亏</span>
                        <span className={(bnStats.net_pnl || 0) >= 0 ? 'dm-stat-profit' : 'dm-stat-loss'}>{bnStats.net_pnl}</span>
                      </div>
                      <div className="dm-stat-item">
                        <span className="dm-stat-label">胜 / 负</span>
                        <span>{bnStats.win_count} / {bnStats.loss_count}</span>
                      </div>
                      <div className="dm-stat-item">
                        <span className="dm-stat-label">胜率</span>
                        <span>{bnStats.win_rate}%</span>
                      </div>
                      <div className="dm-stat-item">
                        <span className="dm-stat-label">笔均盈亏</span>
                        <span>{bnStats.avg_pnl_per_trade}</span>
                      </div>
                      {bnStats.total_quote_qty !== undefined && (
                        <div className="dm-stat-item">
                          <span className="dm-stat-label">总成交额(quoteQty)</span>
                          <span>{bnStats.total_quote_qty}</span>
                        </div>
                      )}
                      {bnStats.maker_count !== undefined && (
                        <div className="dm-stat-item">
                          <span className="dm-stat-label">Maker / Taker</span>
                          <span>{bnStats.maker_count} / {bnStats.taker_count}</span>
                        </div>
                      )}
                      {bnStats.by_symbol && Object.keys(bnStats.by_symbol).length > 0 && (
                        <div className="dm-stat-item dm-stat-wide">
                          <span className="dm-stat-label">按交易对</span>
                          <div className="dm-stat-symbols">
                            {Object.entries(bnStats.by_symbol).map(([sym, v]) => (
                              <span key={sym} className="dm-stat-sym">
                                {sym}: {typeof v === 'object' ? `${v.count}笔, 盈亏${v.pnl}, 成交额${v.quoteQty || v.commission || '-'}` : `${v}笔`}
                              </span>
                            ))}
                          </div>
                        </div>
                      )}
                      {bnStats.by_weekday && Object.keys(bnStats.by_weekday).length > 0 && (
                        <div className="dm-stat-item dm-stat-wide">
                          <span className="dm-stat-label">按星期</span>
                          <div className="dm-stat-symbols">
                            {Object.entries(bnStats.by_weekday).map(([day, v]) => (
                              <span key={day} className="dm-stat-sym">{day}: {v.count}笔, 盈亏{v.pnl}</span>
                            ))}
                          </div>
                        </div>
                      )}
                      {bnStats.by_hour && Object.keys(bnStats.by_hour).length > 0 && (
                        <div className="dm-stat-item dm-stat-wide">
                          <span className="dm-stat-label">按小时(北京)</span>
                          <div className="dm-stat-symbols dm-stat-hours">
                            {Object.entries(bnStats.by_hour).map(([h, v]) => (
                              <span key={h} className="dm-stat-sym">{h}时: {v.count}笔, 盈亏{v.pnl}</span>
                            ))}
                          </div>
                        </div>
                      )}
                    </>
                  )}
                  {!isTrades && (bnStats.by_status || bnStats.filled_count !== undefined) && (
                    <>
                      {bnStats.filled_count !== undefined && (
                        <div className="dm-stat-item">
                          <span className="dm-stat-label">已成交笔数</span>
                          <span>{bnStats.filled_count}</span>
                        </div>
                      )}
                      <div className="dm-stat-item dm-stat-wide">
                        <span className="dm-stat-label">按状态</span>
                        <span>{bnStats.by_status ? Object.entries(bnStats.by_status).map(([k, v]) => `${k}:${v}`).join(', ') : '-'}</span>
                      </div>
                      {bnStats.by_type && (
                        <div className="dm-stat-item dm-stat-wide">
                          <span className="dm-stat-label">按类型</span>
                          <span>{Object.entries(bnStats.by_type).map(([k, v]) => `${k}:${v}`).join(', ')}</span>
                        </div>
                      )}
                      {bnStats.by_symbol && Object.keys(bnStats.by_symbol).length > 0 && (
                        <div className="dm-stat-item dm-stat-wide">
                          <span className="dm-stat-label">按交易对</span>
                          <div className="dm-stat-symbols">
                            {Object.entries(bnStats.by_symbol).slice(0, 20).map(([sym, v]) => (
                              <span key={sym} className="dm-stat-sym">{sym}:{v}笔 </span>
                            ))}
                            {Object.keys(bnStats.by_symbol).length > 20 && <span>...等{Object.keys(bnStats.by_symbol).length}个</span>}
                          </div>
                        </div>
                      )}
                    </>
                  )}
                </div>
              </div>
            )}

            <div className="dm-table-wrap">
              <table className="dm-table">
                <thead>
                  <tr>
                    <th>交易对</th>
                    <th>id</th>
                    <th>orderId</th>
                    <th>side</th>
                    {isTrades ? (
                      <>
                        <th>positionSide</th>
                        <th>出场价</th>
                        <th>推算入场价</th>
                        <th>qty</th>
                        <th>quoteQty</th>
                        <th>realizedPnl</th>
                        <th>commission</th>
                        <th>小时</th>
                        <th>buyer</th>
                        <th>maker</th>
                      </>
                    ) : (
                      <>
                        <th>type</th>
                        <th>status</th>
                        <th>price</th>
                        <th>origQty</th>
                        <th>executedQty</th>
                        <th>avgPrice</th>
                        <th>cumQuote</th>
                        <th>reduceOnly</th>
                      </>
                    )}
                    <th>time</th>
                  </tr>
                </thead>
                <tbody>
                  {bnData.slice(0, 100).map((r, i) => (
                    <tr key={r.id || r.orderId || i}>
                      <td>{r._symbol || r.symbol}</td>
                      <td>{r.id || '-'}</td>
                      <td>{r.orderId}</td>
                      <td>{r.side}</td>
                      {isTrades ? (
                        <>
                          <td>{r.positionSide || '-'}</td>
                          <td>{r.price}</td>
                          <td>{r._approx_entry_price != null ? r._approx_entry_price : '-'}</td>
                          <td>{r.qty}</td>
                          <td>{r.quoteQty}</td>
                          <td className={(r.realizedPnl || 0) >= 0 ? 'dm-profit' : 'dm-loss'}>{r.realizedPnl}</td>
                          <td>{r.commission}</td>
                          <td>{r._trade_hour != null ? `${r._trade_hour}时` : '-'}</td>
                          <td>{r.buyer ? '买' : '卖'}</td>
                          <td>{r.maker ? '是' : '否'}</td>
                        </>
                      ) : (
                        <>
                          <td>{r.type || r.origType}</td>
                          <td>{r.status}</td>
                          <td>{r.price}</td>
                          <td>{r.origQty}</td>
                          <td>{r.executedQty}</td>
                          <td>{r.avgPrice}</td>
                          <td>{r.cumQuote || '-'}</td>
                          <td>{r.reduceOnly ? '是' : '-'}</td>
                        </>
                      )}
                      <td>{r.time ? new Date(r.time).toLocaleString() : r.updateTime ? new Date(r.updateTime).toLocaleString() : '-'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {bnData.length > 100 && (
                <div className="dm-more">仅显示前 100 条，共 {bnResult.total} 条。导出 JSON 含原始全部字段（symbol, id, orderId, side, price, qty, quoteQty, realizedPnl, commission 等）与统计。</div>
              )}
            </div>
          </div>
        )}
      </section>
    </div>
  )
}
