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

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

export function EditItemPage() {
  const { id = '' } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const [item, setItem] = useState<Item | null>(null)
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [itemType, setItemType] = useState<string>('GOOD')
  const [active, setActive] = useState(true)
  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<Error | null>(null)

  useEffect(() => {
    catalog.getItem(id)
      .then((i) => {
        setItem(i)
        setName(i.name)
        setDescription(i.description ?? '')
        setItemType(i.itemType)
        setActive(i.active)
      })
      .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 catalog.updateItem(id, {
        name, itemType, active,
        description: description || null,
      })
      navigate('/items')
    } catch (err: unknown) {
      setError(err instanceof Error ? err : new Error(String(err)))
    } finally {
      setSubmitting(false)
    }
  }

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

  return (
    <div>
      <PageHeader
        title={`Edit ${item.code}`}
        subtitle={`Base UoM: ${item.baseUomCode} (read-only after creation)`}
        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">Name</label>
            <input type="text" required value={name} onChange={(e) => setName(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">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>
        <div>
          <label className="block text-sm font-medium text-slate-700">Description</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>
        <div className="flex items-center gap-2">
          <input type="checkbox" checked={active} onChange={(e) => setActive(e.target.checked)}
            className="rounded border-slate-300" id="active" />
          <label htmlFor="active" className="text-sm text-slate-700">Active</label>
        </div>
        {error && <ErrorBox error={error} />}
        <button type="submit" className="btn-primary" disabled={submitting}>
          {submitting ? 'Saving…' : 'Save Changes'}
        </button>
      </form>
    </div>
  )
}
