import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { identity } from '@/api/client'
import type { User } from '@/types/api'
import { PageHeader } from '@/components/PageHeader'
import { Loading } from '@/components/Loading'
import { ErrorBox } from '@/components/ErrorBox'
import { DataTable, type Column } from '@/components/DataTable'
import { useT } from '@/i18n/LocaleContext'

export function UsersPage() {
  const t = useT()
  const [rows, setRows] = useState<User[]>([])
  const [error, setError] = useState<Error | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    identity
      .listUsers()
      .then(setRows)
      .catch((e: unknown) => setError(e instanceof Error ? e : new Error(String(e))))
      .finally(() => setLoading(false))
  }, [])

  const columns: Column<User>[] = [
    {
      header: t('label.username'),
      key: 'username',
      render: (r) => (
        <Link to={`/users/${r.id}`} className="font-mono text-brand-600 hover:underline">
          {r.username}
        </Link>
      ),
    },
    { header: t('label.displayName'), key: 'displayName' },
    { header: t('label.email'), key: 'email', render: (r) => r.email ?? '\u2014' },
    {
      header: t('label.enabled'),
      key: 'enabled',
      render: (r) =>
        r.enabled ? (
          <span className="text-emerald-600">{t('label.activeStatus')}</span>
        ) : (
          <span className="text-slate-400">{t('label.disabled')}</span>
        ),
    },
  ]

  return (
    <div>
      <PageHeader
        title={t('page.users.title')}
        subtitle={t('page.users.subtitle')}
        actions={<Link to="/users/new" className="btn-primary">{t('action.newUser')}</Link>}
      />
      {loading && <Loading />}
      {error && <ErrorBox error={error} />}
      {!loading && !error && <DataTable rows={rows} columns={columns} />}
    </div>
  )
}
