import { useEffect, useState } from 'react'
import { catalog } from '@/api/client'
import type { Uom } 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 UomsPage() {
  const t = useT()
  const [rows, setRows] = useState<Uom[]>([])
  const [error, setError] = useState<Error | null>(null)
  const [loading, setLoading] = useState(true)

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

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

  return (
    <div>
      <PageHeader
        title={t('page.uoms.title')}
        subtitle={t('page.uoms.subtitle')}
      />
      {loading && <Loading />}
      {error && <ErrorBox error={error} />}
      {!loading && !error && <DataTable rows={rows} columns={columns} />}
    </div>
  )
}
