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

export function EditPurchaseOrderPage() {
  const { id = '' } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const [order, setOrder] = useState<PurchaseOrder | null>(null)
  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(() => {
    purchaseOrders.get(id)
      .then((o) => {
        setOrder(o)
        setExt(o.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 purchaseOrders.update(id, {
        ...(Object.keys(ext).length > 0 ? { ext } : {}),
      })
      navigate(`/purchase-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 ?? 'Purchase order not found'} />

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

  return (
    <div>
      <PageHeader
        title={`Edit ${order.code}`}
        subtitle={`Supplier: ${order.partnerCode} \u00b7 ${order.orderDate} \u00b7 ${order.currencyCode}`}
        actions={<button className="btn-secondary" onClick={() => navigate(`/purchase-orders/${id}`)}>Cancel</button>}
      />
      {!editable ? (
        <div className="card p-6 max-w-2xl">
          <ErrorBox error={`This purchase order is in ${order.status} status and cannot be edited. Only DRAFT orders are editable.`} />
        </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">
            Order code, partner, lines, and currency are read-only after creation.
            Use this form to update custom fields.
          </div>
          <DynamicExtFields entityName="PurchaseOrder" values={ext} onChange={(k, v) => setExt(prev => ({ ...prev, [k]: v }))} />
          {error && <ErrorBox error={error} />}
          <button type="submit" className="btn-primary" disabled={submitting}>
            {submitting ? 'Saving\u2026' : 'Save Changes'}
          </button>
        </form>
      )}
    </div>
  )
}
