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

export function EditSalesOrderPage() {
  const { id = '' } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const t = useT()
  const [order, setOrder] = useState<SalesOrder | 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(() => {
    salesOrders.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 salesOrders.update(id, {
        ...(Object.keys(ext).length > 0 ? { ext } : {}),
      })
      navigate(`/sales-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 ?? 'Sales order not found'} />

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

  return (
    <div>
      <PageHeader
        title={t('page.editSalesOrder.title').replace('{code}', order.code)}
        subtitle={`${t('page.editSalesOrder.subtitle').replace('{partner}', order.partnerCode)} \u00B7 ${order.orderDate} \u00B7 ${order.currencyCode}`}
        actions={<button className="btn-secondary" onClick={() => navigate(`/sales-orders/${id}`)}>{t('action.cancel')}</button>}
      />
      {!editable ? (
        <div className="card p-6 max-w-2xl">
          <ErrorBox error={t('page.editSalesOrder.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.editSalesOrder.readOnlyHint')}
          </div>
          <DynamicExtFields entityName="SalesOrder" 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>
  )
}
