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'

export function LocationsPage() {
  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: 'Code', key: 'code', render: (r) => <span className="font-mono">{r.code}</span> },
    { header: 'Name', key: 'name' },
    { header: 'Type', key: 'type' },
    {
      header: 'Active',
      key: 'active',
      render: (r) => (r.active ? <span className="text-emerald-600">●</span> : <span className="text-slate-300">●</span>),
    },
  ]

  return (
    <div>
      <PageHeader
        title="Locations"
        subtitle="Warehouses, bins, and virtual locations the inventory PBC tracks."
        actions={<Link to="/locations/new" className="btn-primary">+ New Location</Link>}
      />
      {loading && <Loading />}
      {error && <ErrorBox error={error} />}
      {!loading && !error && <DataTable rows={rows} columns={columns} />}
    </div>
  )
}
