// UoM selector widget for @rjsf forms.
// Fetches units of measure from the API and renders a <select> dropdown
// showing "code -- name" for each UoM.

import { useEffect, useState } from 'react'
import type { WidgetProps } from '@rjsf/utils'
import { catalog } from '@/api/client'
import type { Uom } from '@/types/api'

export function UomSelector(props: WidgetProps) {
  const { id, value, required, disabled, readonly, onChange } = props
  const [uoms, setUoms] = useState<Uom[]>([])

  useEffect(() => {
    catalog.listUoms().then(setUoms).catch(() => setUoms([]))
  }, [])

  return (
    <select
      id={id}
      value={value ?? ''}
      required={required}
      disabled={disabled || readonly}
      onChange={(e) => onChange(e.target.value || undefined)}
      className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm"
    >
      <option value="">—</option>
      {uoms.map((u) => (
        <option key={u.id} value={u.code}>
          {u.code} — {u.name}
        </option>
      ))}
    </select>
  )
}
