import { useEffect, useState, type FormEvent } from 'react'
import { useNavigate, useParams } 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 { DynamicExtFields } from '@/components/DynamicExtFields'
import { useT } from '@/i18n/LocaleContext'

export function EditWorkOrderPage() {
  const { id = '' } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const t = useT()
  const [order, setOrder] = useState<WorkOrder | null>(null)
  const [outputQuantity, setOutputQuantity] = useState('')
  const [dueDate, setDueDate] = useState('')
  const [loading, setLoading] = useState(true)
  const [ext, setExt] = useState<Record<string, unknown>>({})
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<Error | null>(null)

  useEffect(() => {
    production.getWorkOrder(id)
      .then((wo) => {
        setOrder(wo)
        setOutputQuantity(String(wo.outputQuantity))
        setDueDate(wo.dueDate ?? '')
        setExt(wo.ext || {})
      })
      .catch((e: unknown) => setError(e instanceof Error ? e : new Error(String(e))))
      .finally(() => setLoading(false))
  }, [id])

  const onSubmit = async (e: FormEvent) => {
    e.preventDefault()
    setError(null)
    setSubmitting(true)
    try {
      await production.updateWorkOrder(id, {
        outputQuantity: Number(outputQuantity),
        dueDate: dueDate || null,
        ...(Object.keys(ext).length > 0 ? { ext } : {}),
      })
      navigate(`/work-orders/${id}`)
    } catch (err: unknown) {
      setError(err instanceof Error ? err : new Error(String(err)))
    } finally {
      setSubmitting(false)
    }
  }

  if (loading) return <Loading />
  if (!order) return <ErrorBox error={error ?? 'Work order not found'} />

  const editable = order.status === 'DRAFT'

  return (
    <div>
      <PageHeader
        title={t('page.editWorkOrder.title').replace('{code}', order.code)}
        subtitle={t('page.editWorkOrder.subtitle').replace('{item}', order.outputItemCode)}
        actions={<button className="btn-secondary" onClick={() => navigate(`/work-orders/${id}`)}>{t('action.cancel')}</button>}
      />
      {!editable ? (
        <div className="card p-6 max-w-2xl">
          <ErrorBox error={t('page.editWorkOrder.notEditable').replace('{status}', order.status)} />
        </div>
      ) : (
        <form onSubmit={onSubmit} className="card p-6 space-y-4 max-w-2xl">
          <div className="rounded-md border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-600">
            {t('page.editWorkOrder.readOnlyHint')}
          </div>
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <div>
              <label className="block text-sm font-medium text-slate-700">{t('label.outputQty')}</label>
              <input type="number" required min="1" step="any" value={outputQuantity}
                onChange={(e) => setOutputQuantity(e.target.value)}
                className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm" />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700">{t('label.dueDate')}</label>
              <input type="date" value={dueDate} onChange={(e) => setDueDate(e.target.value)}
                className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm" />
            </div>
          </div>
          <DynamicExtFields entityName="WorkOrder" values={ext} onChange={(k, v) => setExt(prev => ({ ...prev, [k]: v }))} />
          {error && <ErrorBox error={error} />}
          <button type="submit" className="btn-primary" disabled={submitting}>
            {submitting ? t('action.saving') : t('action.saveChanges')}
          </button>
        </form>
      )}
    </div>
  )
}
