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'
import { useT } from '@/i18n/LocaleContext'

export function WorkOrdersPage() {
  const t = useT()
  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: t('label.code'),
      key: 'code',
      render: (r) => (
        <Link to={`/work-orders/${r.id}`} className="font-mono text-brand-600 hover:underline">
          {r.code}
        </Link>
      ),
    },
    { header: t('label.output'), key: 'outputItemCode', render: (r) => <span className="font-mono">{r.outputItemCode}</span> },
    {
      header: t('label.qty'),
      key: 'outputQuantity',
      render: (r) => <span className="font-mono tabular-nums">{String(r.outputQuantity)}</span>,
    },
    { header: t('label.status'), key: 'status', render: (r) => <StatusBadge status={r.status} /> },
    {
      header: t('label.sourceSO'),
      key: 'sourceSalesOrderCode',
      render: (r) => r.sourceSalesOrderCode ?? '\u2014',
    },
    {
      header: t('label.inputsOps'),
      key: 'opsCount',
      render: (r) => `${r.inputs.length} / ${r.operations.length}`,
    },
  ]

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