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

  useEffect(() => {
    production
      .listWorkOrders()
      .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<WorkOrder>[] = [
    {
      header: 'Code',
      key: 'code',
      render: (r) => (
        <Link to={`/work-orders/${r.id}`} className="font-mono text-brand-600 hover:underline">
          {r.code}
        </Link>
      ),
    },
    { header: 'Output', key: 'outputItemCode', render: (r) => <span className="font-mono">{r.outputItemCode}</span> },
    {
      header: 'Qty',
      key: 'outputQuantity',
      render: (r) => <span className="font-mono tabular-nums">{String(r.outputQuantity)}</span>,
    },
    { header: 'Status', key: 'status', render: (r) => <StatusBadge status={r.status} /> },
    {
      header: 'Source SO',
      key: 'sourceSalesOrderCode',
      render: (r) => r.sourceSalesOrderCode ?? '—',
    },
    {
      header: 'Inputs / Ops',
      key: 'opsCount',
      render: (r) => `${r.inputs.length} / ${r.operations.length}`,
    },
  ]

  return (
    <div>
      <PageHeader title="Work Orders" subtitle="Production orders the framework consumes inputs and produces outputs through." />
      {loading && <Loading />}
      {error && <ErrorBox error={error} />}
      {!loading && !error && <DataTable rows={rows} columns={columns} />}
    </div>
  )
}
