import { useEffect, useState, type FormEvent } from 'react'
import { identity } from '@/api/client'
import type { Role } 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 RolesPage() {
  const t = useT()
  const [rows, setRows] = useState<Role[]>([])
  const [error, setError] = useState<Error | null>(null)
  const [loading, setLoading] = useState(true)
  const [showCreate, setShowCreate] = useState(false)
  const [code, setCode] = useState('')
  const [name, setName] = useState('')
  const [creating, setCreating] = useState(false)

  const load = () => {
    identity
      .listRoles()
      .then(setRows)
      .catch((e: unknown) => setError(e instanceof Error ? e : new Error(String(e))))
      .finally(() => setLoading(false))
  }

  useEffect(() => { load() }, []) // eslint-disable-line react-hooks/exhaustive-deps

  const onCreate = async (e: FormEvent) => {
    e.preventDefault()
    setCreating(true)
    setError(null)
    try {
      await identity.createRole({ code, name })
      setCode('')
      setName('')
      setShowCreate(false)
      load()
    } catch (err: unknown) {
      setError(err instanceof Error ? err : new Error(String(err)))
    } finally {
      setCreating(false)
    }
  }

  const columns: Column<Role>[] = [
    { header: t('label.code'), key: 'code', render: (r) => <span className="font-mono">{r.code}</span> },
    { header: t('label.name'), key: 'name' },
    { header: t('label.description'), key: 'description', render: (r) => r.description ?? '\u2014' },
  ]

  return (
    <div>
      <PageHeader
        title={t('page.roles.title')}
        subtitle={t('page.roles.subtitle')}
        actions={
          <button className="btn-primary" onClick={() => setShowCreate(!showCreate)}>
            {showCreate ? t('action.cancel') : t('action.newRole')}
          </button>
        }
      />
      {showCreate && (
        <form onSubmit={onCreate} className="card p-4 mb-4 max-w-lg flex items-end gap-3">
          <div className="flex-1">
            <label className="block text-xs font-medium text-slate-700">{t('label.code')}</label>
            <input type="text" required value={code} onChange={(e) => setCode(e.target.value)}
              placeholder="sales-clerk" className="mt-1 w-full rounded-md border border-slate-300 px-2 py-1.5 text-sm" />
          </div>
          <div className="flex-1">
            <label className="block text-xs font-medium text-slate-700">{t('label.name')}</label>
            <input type="text" required value={name} onChange={(e) => setName(e.target.value)}
              placeholder="Sales Clerk" className="mt-1 w-full rounded-md border border-slate-300 px-2 py-1.5 text-sm" />
          </div>
          <button type="submit" className="btn-primary" disabled={creating}>
            {creating ? '...' : t('action.create')}
          </button>
        </form>
      )}
      {loading && <Loading />}
      {error && <ErrorBox error={error} />}
      {!loading && !error && <DataTable rows={rows} columns={columns} />}
    </div>
  )
}
