/**
 * 管理员共用组件：用户管理、系统账号管理
 */
import React, { useState } from 'react'
import { api } from '../services/api'
import './AdminDashboard.css'

export const UserAccountGroup = ({ user, allAccounts, onServiceAction }) => {
  const [expanded, setExpanded] = useState(true)
  const [processing, setProcessing] = useState(false)
  const [linkAccountId, setLinkAccountId] = useState('')
  const [linkRole, setLinkRole] = useState('viewer')
  const [associating, setAssociating] = useState(false)

  const handleUserAction = async (action) => {
    if (!window.confirm(`确定要${action === 'start' ? '启动' : '停止'}用户 ${user.username} 下所有账号的交易服务吗？`)) return
    setProcessing(true)
    try {
      const promises = user.accounts.map(acc =>
        api.post(`/accounts/${acc.id}/service/${action}`).catch(e => console.error(`Failed to ${action} account ${acc.id}:`, e))
      )
      await Promise.all(promises)
      if (onServiceAction) onServiceAction(null, 'refresh')
    } catch (e) {
      alert(`操作失败: ${e.message}`)
    } finally {
      setProcessing(false)
    }
  }

  const handleGrant = async () => {
    if (!linkAccountId) return
    const accountId = Number(linkAccountId)
    if (!Number.isInteger(accountId) || accountId < 1) {
      alert('请选择有效的账号')
      return
    }
    setAssociating(true)
    try {
      await api.grantUserAccount(user.id, accountId, linkRole)
      setLinkAccountId('')
      if (onServiceAction) onServiceAction(null, 'refresh')
    } catch (e) {
      alert(`关联失败: ${e.message}`)
    } finally {
      setAssociating(false)
    }
  }

  const handleRevoke = async (accountId) => {
    if (!window.confirm('确定要取消该账号的关联吗？')) return
    try {
      await api.revokeUserAccount(user.id, accountId)
      if (onServiceAction) onServiceAction(null, 'refresh')
    } catch (e) {
      alert(`取消关联失败: ${e.message}`)
    }
  }

  const allRunning = user.accounts.every(a => a.serviceStatus?.running)
  const allStopped = user.accounts.every(a => !a.serviceStatus?.running)
  const availableAccounts = (allAccounts || []).filter(a => !user.accounts.some(ua => ua.id === a.id))

  return (
    <div className="user-group-card">
      <div className="user-group-header" onClick={() => setExpanded(!expanded)}>
        <div className="user-info">
          <span className={`expand-icon ${expanded ? 'expanded' : ''}`}>▶</span>
          <span className="user-name">{user.username}</span>
          <span className={`user-role-badge ${user.role}`}>{user.role}</span>
          <span className="account-count">({user.accounts.length} 账号)</span>
        </div>
        {user.role !== 'admin' && (
          <div className="user-actions" onClick={e => e.stopPropagation()}>
            <button className="btn-text-action start" onClick={() => handleUserAction('start')} disabled={processing || allRunning || user.accounts.length === 0}>全部启动</button>
            <button className="btn-text-action stop" onClick={() => handleUserAction('stop')} disabled={processing || allStopped || user.accounts.length === 0}>全部停止</button>
          </div>
        )}
      </div>
      {expanded && user.role !== 'admin' && (
        <div className="user-accounts-table">
          {user.accounts.length === 0 ? (
            <div className="no-accounts">暂无关联账号</div>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>ID</th><th>名称</th><th>权限</th><th>账户状态</th><th>服务状态</th><th>总资产</th><th>总盈亏</th><th>持仓数</th><th>操作</th>
                </tr>
              </thead>
              <tbody>
                {user.accounts.map(acc => (
                  <tr key={acc.id}>
                    <td>{acc.id}</td>
                    <td>{acc.name}</td>
                    <td><span className="role-tag">{acc.role || 'viewer'}</span></td>
                    <td><span className={`status-badge ${acc.status}`}>{acc.status === 'active' ? '启用' : '禁用'}</span></td>
                    <td>
                      {acc.serviceStatus ? (
                        <span className={`status-badge ${acc.serviceStatus.running ? 'running' : 'stopped'}`}>{acc.serviceStatus.running ? '运行中' : '停止'}</span>
                      ) : (
                        <span className="status-badge stopped">未启动</span>
                      )}
                    </td>
                    <td>{acc.total_balance?.toFixed(2) || '-'}</td>
                    <td className={acc.total_pnl >= 0 ? 'profit' : 'loss'}>{acc.total_pnl?.toFixed(2) || '-'}</td>
                    <td>{acc.open_positions || 0}</td>
                    <td>
                      <button className="btn-icon" onClick={() => onServiceAction && onServiceAction(acc.id, acc.serviceStatus?.running ? 'stop' : 'start')} title={acc.serviceStatus?.running ? '停止服务' : '启动服务'}>
                        {acc.serviceStatus?.running ? '⏹' : '▶'}
                      </button>
                      <button className="btn-icon danger" onClick={() => handleRevoke(acc.id)} title="取消关联" style={{ marginLeft: '8px' }}>✕</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
          <div className="add-account-section">
            <h4>新增关联</h4>
            <div className="add-account-form">
              <select value={linkAccountId} onChange={e => setLinkAccountId(e.target.value)} disabled={associating}>
                <option value="">选择账号...</option>
                {availableAccounts.map(a => (
                  <option key={a.id} value={a.id}>#{a.id} {a.name} ({a.status === 'active' ? '启用' : '禁用'})</option>
                ))}
              </select>
              <select value={linkRole} onChange={e => setLinkRole(e.target.value)} disabled={associating}>
                <option value="viewer">观察者 (Viewer)</option>
                <option value="owner">拥有者 (Owner)</option>
              </select>
              <button onClick={handleGrant} disabled={!linkAccountId || associating} className="btn-primary">{associating ? '关联中...' : '关联'}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export const CreateUserForm = ({ onSuccess }) => {
  const [form, setForm] = useState({ username: '', password: '', role: 'user', status: 'active' })
  const [busy, setBusy] = useState(false)
  const [message, setMessage] = useState('')
  const handleCreate = async () => {
    if (!form.username.trim()) { setMessage('请输入用户名'); return }
    if (!form.password.trim()) { setMessage('请输入密码'); return }
    setBusy(true)
    setMessage('')
    try {
      await api.createUser({ username: form.username.trim(), password: form.password, role: form.role, status: form.status })
      setMessage('用户已创建')
      setForm({ username: '', password: '', role: 'user', status: 'active' })
      if (onSuccess) onSuccess()
    } catch (e) {
      setMessage('创建用户失败: ' + (e?.message || '未知错误'))
    } finally {
      setBusy(false)
    }
  }
  return (
    <div className="card create-user-card">
      <h4 className="create-user-card-heading">新建用户</h4>
      {message && <div className={`message ${message.includes('失败') ? 'error' : 'success'}`}>{message}</div>}
      <div className="form-group">
        <label>用户名</label>
        <input type="text" value={form.username} onChange={(e) => setForm({ ...form, username: e.target.value })} placeholder="登录用，例如：trader1" />
      </div>
      <div className="form-group">
        <label>密码</label>
        <input type="password" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} placeholder="设置登录密码" />
      </div>
      <div className="form-group">
        <label>角色</label>
        <select value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value })}>
          <option value="user">普通用户 (user)</option>
          <option value="admin">管理员 (admin)</option>
        </select>
      </div>
      <div className="form-group">
        <label>状态</label>
        <select value={form.status} onChange={(e) => setForm({ ...form, status: e.target.value })}>
          <option value="active">启用</option>
          <option value="disabled">禁用</option>
        </select>
      </div>
      <button className="btn-primary full-width" onClick={handleCreate} disabled={busy || !form.username.trim() || !form.password}>{busy ? '创建中...' : '创建用户'}</button>
    </div>
  )
}

export const AccountManager = ({ accounts, onRefresh }) => {
  const [newAccount, setNewAccount] = useState({ name: '', api_key: '', api_secret: '', use_testnet: false, status: 'active' })
  const [credEditId, setCredEditId] = useState(null)
  const [credForm, setCredForm] = useState({ api_key: '', api_secret: '', use_testnet: false })
  const [busy, setBusy] = useState(false)
  const [message, setMessage] = useState('')
  const notifyAccountsUpdated = () => {
    try { window.dispatchEvent(new Event('ats:accounts:updated')) } catch (e) { /* ignore */ }
  }
  const handleCreate = async () => {
    if (!newAccount.name.trim()) return
    setBusy(true)
    setMessage('')
    try {
      await api.createAccount(newAccount)
      setMessage('账号已创建')
      setNewAccount({ name: '', api_key: '', api_secret: '', use_testnet: false, status: 'active' })
      if (onRefresh) onRefresh()
      notifyAccountsUpdated()
    } catch (e) {
      setMessage('创建账号失败: ' + (e?.message || '未知错误'))
    } finally {
      setBusy(false)
    }
  }
  const handleUpdateStatus = async (account) => {
    setBusy(true)
    setMessage('')
    try {
      const next = account.status === 'active' ? 'disabled' : 'active'
      await api.updateAccount(account.id, { status: next })
      setMessage(`账号 #${account.id} 已${next === 'active' ? '启用' : '禁用'}`)
      if (onRefresh) onRefresh()
      notifyAccountsUpdated()
    } catch (e) {
      setMessage('更新账号失败: ' + (e?.message || '未知错误'))
    } finally {
      setBusy(false)
    }
  }
  const handleUpdateCreds = async () => {
    if (!credEditId) return
    setBusy(true)
    setMessage('')
    try {
      const payload = {}
      if (credForm.api_key) payload.api_key = credForm.api_key
      if (credForm.api_secret) payload.api_secret = credForm.api_secret
      payload.use_testnet = !!credForm.use_testnet
      await api.updateAccountCredentials(credEditId, payload)
      setMessage(`账号 #${credEditId} 密钥已更新`)
      setCredEditId(null)
      if (onRefresh) onRefresh()
      notifyAccountsUpdated()
    } catch (e) {
      setMessage('更新密钥失败: ' + (e?.message || '未知错误'))
    } finally {
      setBusy(false)
    }
  }
  return (
    <div className="accounts-manager-section">
      <h3>系统账号池管理</h3>
      {message && <div className={`message ${message.includes('失败') ? 'error' : 'success'}`}>{message}</div>}
      <div className="accounts-manager-grid">
        <div className="card create-account-card">
          <h4>新增账号</h4>
          <div className="form-group">
            <label>名称</label>
            <input type="text" value={newAccount.name} onChange={(e) => setNewAccount({ ...newAccount, name: e.target.value })} placeholder="例如：user_a" />
          </div>
          <div className="form-group">
            <label>API KEY (可选)</label>
            <input type="password" value={newAccount.api_key} onChange={(e) => setNewAccount({ ...newAccount, api_key: e.target.value })} />
          </div>
          <div className="form-group">
            <label>API SECRET (可选)</label>
            <input type="password" value={newAccount.api_secret} onChange={(e) => setNewAccount({ ...newAccount, api_secret: e.target.value })} />
          </div>
          <div className="form-group checkbox">
            <label><input type="checkbox" checked={!!newAccount.use_testnet} onChange={(e) => setNewAccount({ ...newAccount, use_testnet: e.target.checked })} />测试网</label>
          </div>
          <div className="form-group">
            <label>初始状态</label>
            <select value={newAccount.status} onChange={(e) => setNewAccount({ ...newAccount, status: e.target.value })}>
              <option value="active">启用</option>
              <option value="disabled">禁用</option>
            </select>
          </div>
          <button className="btn-primary full-width" onClick={handleCreate} disabled={busy || !newAccount.name.trim()}>创建账号</button>
        </div>
        <div className="card account-list-card">
          <h4>账号列表 ({accounts?.length || 0})</h4>
          <div className="table-wrapper">
            <table className="data-table">
              <thead>
                <tr><th>ID</th><th>名称</th><th>状态</th><th>测试网</th><th>API配置</th><th>操作</th></tr>
              </thead>
              <tbody>
                {(accounts || []).map(a => (
                  <tr key={a.id}>
                    <td>#{a.id}</td>
                    <td>{a.name}</td>
                    <td><span className={`status-badge ${a.status}`}>{a.status === 'active' ? '启用' : '禁用'}</span></td>
                    <td>{a.use_testnet ? '是' : '否'}</td>
                    <td>{a.has_api_key ? '✅' : '❌'} / {a.has_api_secret ? '✅' : '❌'}</td>
                    <td>
                      <div className="action-buttons">
                        <button className="btn-sm" disabled={busy || a.id === 1} onClick={() => handleUpdateStatus(a)} title={a.id === 1 ? '默认账号不可禁用' : '切换状态'}>{a.status === 'active' ? '禁用' : '启用'}</button>
                        <button className="btn-sm" disabled={busy} onClick={() => { setCredEditId(a.id); setCredForm({ api_key: '', api_secret: '', use_testnet: !!a.use_testnet }) }}>密钥</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
      {credEditId && (
        <div className="modal-overlay">
          <div className="modal-content">
            <h4>更新密钥 (账号 #{credEditId})</h4>
            <div className="form-group">
              <label>API KEY (留空=不改)</label>
              <input type="password" value={credForm.api_key} onChange={(e) => setCredForm({ ...credForm, api_key: e.target.value })} />
            </div>
            <div className="form-group">
              <label>API SECRET (留空=不改)</label>
              <input type="password" value={credForm.api_secret} onChange={(e) => setCredForm({ ...credForm, api_secret: e.target.value })} />
            </div>
            <div className="form-group checkbox">
              <label><input type="checkbox" checked={!!credForm.use_testnet} onChange={(e) => setCredForm({ ...credForm, use_testnet: e.target.checked })} />测试网</label>
            </div>
            <div className="modal-actions">
              <button className="btn-secondary" onClick={() => setCredEditId(null)}>取消</button>
              <button className="btn-primary" onClick={handleUpdateCreds} disabled={busy}>保存</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
