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

  useEffect(() => {
    salesOrders
      .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<SalesOrder>[] = [
    {
      header: 'Code',
      key: 'code',
      render: (r) => (
        <Link to={`/sales-orders/${r.id}`} className="font-mono text-brand-600 hover:underline">
          {r.code}
        </Link>
      ),
    },
    { header: 'Customer', key: 'partnerCode', render: (r) => <span className="font-mono">{r.partnerCode}</span> },
    { header: 'Date', key: 'orderDate' },
    { 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,
            maximumFractionDigits: 2,
          })}{' '}
          {r.currencyCode}
        </span>
      ),
    },
    {
      header: 'Lines',
      key: 'lines',
      render: (r) => <span className="text-slate-500">{r.lines.length}</span>,
    },
  ]

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