import { useEffect, useState, type FormEvent } from 'react'
import { useNavigate } from 'react-router-dom'
import { catalog } from '@/api/client'
import type { Uom } from '@/types/api'
import { PageHeader } from '@/components/PageHeader'
import { ErrorBox } from '@/components/ErrorBox'
import { DynamicExtFields } from '@/components/DynamicExtFields'

const ITEM_TYPES = ['GOOD', 'SERVICE', 'DIGITAL'] as const

export function CreateItemPage() {
  const navigate = useNavigate()
  const [code, setCode] = useState('')
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [itemType, setItemType] = useState<string>('GOOD')
  const [baseUomCode, setBaseUomCode] = useState('')
  const [uoms, setUoms] = useState<Uom[]>([])
  const [ext, setExt] = useState<Record<string, unknown>>({})
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<Error | null>(null)

  useEffect(() => {
    catalog.listUoms().then((u) => {
      setUoms(u)
      if (u.length > 0 && !baseUomCode) setBaseUomCode(u[0].code)
    })
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  const onSubmit = async (e: FormEvent) => {
    e.preventDefault()
    setError(null)
    setSubmitting(true)
    try {
      const extPayload = Object.keys(ext).length > 0 ? ext : undefined
      await catalog.createItem({
        code, name, itemType, baseUomCode,
        description: description || null,
        ...(extPayload ? { ext: extPayload } : {}),
      } as Parameters<typeof catalog.createItem>[0])
      navigate('/items')
    } catch (err: unknown) {
      setError(err instanceof Error ? err : new Error(String(err)))
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div>
      <PageHeader
        title="New Item"
        subtitle="Add a raw material, finished good, or service to the catalog."
        actions={<button className="btn-secondary" onClick={() => navigate('/items')}>Cancel</button>}
      />
      <form onSubmit={onSubmit} className="card p-6 space-y-4 max-w-2xl">
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
          <div>
            <label className="block text-sm font-medium text-slate-700">Item code</label>
            <input type="text" required value={code} onChange={(e) => setCode(e.target.value)}
              placeholder="PAPER-120G-A3" 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">Name</label>
            <input type="text" required value={name} onChange={(e) => setName(e.target.value)}
              placeholder="120g A3 coated paper" 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">Type</label>
            <select value={itemType} onChange={(e) => setItemType(e.target.value)}
              className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm">
              {ITEM_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-700">Base UoM</label>
            <select value={baseUomCode} onChange={(e) => setBaseUomCode(e.target.value)}
              className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm">
              {uoms.map((u) => <option key={u.id} value={u.code}>{u.code} — {u.name}</option>)}
            </select>
          </div>
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700">Description (optional)</label>
          <input type="text" value={description} onChange={(e) => setDescription(e.target.value)}
            className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm" />
        </div>
        <DynamicExtFields
          entityName="Item"
          values={ext}
          onChange={(k, v) => setExt((prev) => ({ ...prev, [k]: v }))}
        />
        {error && <ErrorBox error={error} />}
        <button type="submit" className="btn-primary" disabled={submitting}>
          {submitting ? 'Creating...' : 'Create Item'}
        </button>
      </form>
    </div>
  )
}
