import { Loading, ErrorState } from '../../../components/PageState.jsx'
import { useAsync } from '../../../lib/useAsync.js'
import { dateTime } from '../../../lib/format.js'
import { api } from '../../../api/client.js'
import { formatDetail } from './Dashboard.jsx'

export default function ActivityAdmin() {
  const { loading, error, data } = useAsync(() => api.admin.activity(100))
  const rows = data || []

  if (loading) return <Loading />
  if (error) return <ErrorState message="Could not load the activity log." />

  return (
    <section>
      <div className="panel-flat">
        <table className="adm-table">
          <thead>
            <tr>
              <th className="adm-th">Action</th>
              <th className="adm-th">Detail</th>
              <th className="adm-th">User</th>
              <th className="adm-th">IP</th>
              <th className="adm-th">When</th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 && (
              <tr>
                <td className="adm-td" colSpan={5} style={{ color: 'var(--muted)' }}>
                  No activity recorded yet.
                </td>
              </tr>
            )}
            {rows.map((a) => (
              <tr key={a.id}>
                <td className="adm-td">
                  <span style={{ fontFamily: 'ui-monospace,Menlo,monospace', color: 'var(--accent)', fontSize: '0.82rem' }}>
                    {a.action}
                  </span>
                </td>
                <td className="adm-td">{formatDetail(a)}</td>
                <td className="adm-td" style={{ color: 'var(--text)' }}>
                  {a.username || '—'}
                </td>
                <td className="adm-td dim" style={{ fontFamily: 'ui-monospace,Menlo,monospace', fontSize: '0.8rem' }}>
                  {a.ip || '—'}
                </td>
                <td className="adm-td dim">{dateTime(a.created_at)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  )
}
