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

export default function AdminAccountManagement() {
  const [accounts, setAccounts] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  const loadData = async () => {
    try {
      const res = await api.get('/accounts').catch(() => ({ data: [] }))
      setAccounts(res.data || [])
      setError(null)
    } catch (err) {
      setError(err?.message)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadData()
    const onUpdated = () => loadData()
    window.addEventListener('ats:accounts:updated', onUpdated)
    return () => window.removeEventListener('ats:accounts:updated', onUpdated)
  }, [])

  if (loading && accounts.length === 0) return <div className="loading">加载中...</div>
  if (error) return <div className="error">加载失败: {error}</div>

  return (
    <div className="admin-dashboard">
      <div className="dashboard-header">
        <h2>系统账号管理</h2>
        <button className="refresh-btn" onClick={loadData}>刷新</button>
      </div>
      <AccountManager accounts={accounts} onRefresh={loadData} />
    </div>
  )
}
