import { useCallback, useState } from 'react'
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 UserEditor from './UserEditor.jsx'

const ROLE_BADGE = { admin: 'badge-admin', editor: 'badge-editor', moderator: 'badge-moderator' }

export default function UsersAdmin() {
  const [tick, setTick] = useState(0)
  const reload = useCallback(() => setTick((t) => t + 1), [])
  const { loading, error, data } = useAsync(() => api.admin.listUsers(), [tick])
  const [editing, setEditing] = useState(null) // null | 'new' | user
  const users = data || []

  return (
    <section>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18, flexWrap: 'wrap', gap: 12 }}>
        <p className="sans muted" style={{ margin: 0, fontSize: '0.9rem' }}>
          Manage admin, editor, and moderator accounts
        </p>
        <button onClick={() => setEditing('new')} className="btn btn-primary btn-sq">
          + Add user
        </button>
      </div>

      {loading && <Loading />}
      {error && <ErrorState message="Could not load users." />}

      {!loading && !error && (
        <div className="panel-flat">
          <table className="adm-table">
            <thead>
              <tr>
                <th className="adm-th">Username</th>
                <th className="adm-th">Role</th>
                <th className="adm-th">Last login</th>
                <th className="adm-th" />
              </tr>
            </thead>
            <tbody>
              {users.map((u) => (
                <tr key={u.id}>
                  <td className="adm-td" style={{ color: 'var(--head)' }}>
                    {u.username}
                  </td>
                  <td className="adm-td">
                    <span className={`badge ${ROLE_BADGE[u.role] || 'badge-editor'}`}>{u.role}</span>
                  </td>
                  <td className="adm-td dim">{u.last_login_at ? dateTime(u.last_login_at) : 'never'}</td>
                  <td className="adm-td" style={{ textAlign: 'right' }}>
                    <span className="link-accent" onClick={() => setEditing(u)}>
                      Edit
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {editing && (
        <UserEditor
          user={editing === 'new' ? null : editing}
          onClose={() => setEditing(null)}
          onSaved={() => {
            setEditing(null)
            reload()
          }}
        />
      )}
    </section>
  )
}
