import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { api } from '../api/client.js'

export default function Admin() {
  const [accounts, setAccounts] = useState([])
  const [err, setErr] = useState('')

  useEffect(() => {
    api
      .listAccounts()
      .then((rows) => setAccounts(Array.isArray(rows) ? rows : []))
      .catch((e) => setErr(e.message))
  }, [])

  return (
    <div className="main-inner">
      <h1 className="page-title">概览</h1>
      <p className="muted">共 {accounts.length} 个邮箱账户</p>

      {err && (
        <div className="card" style={{ color: 'var(--danger)' }}>
          {err}
        </div>
      )}

      <div className="card">
        {accounts.length === 0 ? (
          <p className="muted">
            暂无账户，前往 <Link to="/admin/accounts">管理账户</Link> 添加。
          </p>
        ) : (
          <table>
            <thead>
              <tr>
                <th>名称</th>
                <th>邮箱</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {accounts.map((a) => (
                <tr key={a.id}>
                  <td>{a.name}</td>
                  <td>{a.email}</td>
                  <td>
                    <Link to={`/admin/mailbox/${a.id}`}>打开</Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  )
}
