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

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

  const columns: Column<Location>[] = [
    { header: t('label.code'), key: 'code', render: (r) => <span className="font-mono">{r.code}</span> },
    { header: t('label.name'), key: 'name' },
    { header: t('label.type'), key: 'type' },
    {
      header: t('label.active'),
      key: 'active',
      render: (r) => (r.active ? <span className="text-emerald-600">{'\u25CF'}</span> : <span className="text-slate-300">{'\u25CF'}</span>),
    },
  ]

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