import { useEffect, useState } from 'react'
import { catalog } from '@/api/client'
import type { Item } 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'

export function ItemsPage() {
  const [rows, setRows] = useState<Item[]>([])
  const [error, setError] = useState<Error | null>(null)
  const [loading, setLoading] = useState(true)

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

  const columns: Column<Item>[] = [
    { header: 'Code', key: 'code', render: (r) => <span className="font-mono">{r.code}</span> },
    { header: 'Name', key: 'name' },
    { header: 'Type', key: 'itemType' },
    { header: 'UoM', key: 'baseUomCode', render: (r) => <span className="font-mono">{r.baseUomCode}</span> },
    {
      header: 'Active',
      key: 'active',
      render: (r) => (r.active ? <span className="text-emerald-600">●</span> : <span className="text-slate-300">●</span>),
    },
  ]

  return (
    <div>
      <PageHeader
        title="Items"
        subtitle="Catalog of items the framework can transact: raw materials, components, finished goods, services."
      />
      {loading && <Loading />}
      {error && <ErrorBox error={error} />}
      {!loading && !error && <DataTable rows={rows} columns={columns} />}
    </div>
  )
}
