import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { purchaseOrders } from '@/api/client'
import type { PurchaseOrder } 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 { StatusBadge } from '@/components/StatusBadge'

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

  useEffect(() => {
    purchaseOrders
      .list()
      .then((rs) => setRows([...rs].sort((a, b) => a.code.localeCompare(b.code))))
      .catch((e: unknown) => setError(e instanceof Error ? e : new Error(String(e))))
      .finally(() => setLoading(false))
  }, [])

  const columns: Column<PurchaseOrder>[] = [
    {
      header: 'Code',
      key: 'code',
      render: (r) => (
        <Link to={`/purchase-orders/${r.id}`} className="font-mono text-brand-600 hover:underline">
          {r.code}
        </Link>
      ),
    },
    { header: 'Supplier', key: 'partnerCode', render: (r) => <span className="font-mono">{r.partnerCode}</span> },
    { header: 'Order date', key: 'orderDate' },
    { header: 'Expected', key: 'expectedDate', render: (r) => r.expectedDate ?? '—' },
    { header: 'Status', key: 'status', render: (r) => <StatusBadge status={r.status} /> },
    {
      header: 'Total',
      key: 'totalAmount',
      render: (r) => (
        <span className="font-mono tabular-nums">
          {Number(r.totalAmount).toLocaleString(undefined, {
            minimumFractionDigits: 2,
          })}{' '}
          {r.currencyCode}
        </span>
      ),
    },
  ]

  return (
    <div>
      <PageHeader title="Purchase Orders" subtitle="Supplier-facing orders. Click a code to drill in." />
      {loading && <Loading />}
      {error && <ErrorBox error={error} />}
      {!loading && !error && <DataTable rows={rows} columns={columns} />}
    </div>
  )
}
