// Item picker widget for @rjsf forms.
// Fetches catalog items from the API and renders a <select> dropdown
// showing "code -- name" for each item.

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

export function ItemPicker(props: WidgetProps) {
  const { id, value, required, disabled, readonly, onChange } = props
  const [items, setItems] = useState<Item[]>([])

  useEffect(() => {
    catalog.listItems().then(setItems).catch(() => setItems([]))
  }, [])

  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>
      {items.map((item) => (
        <option key={item.id} value={item.code}>
          {item.code} — {item.name}
        </option>
      ))}
    </select>
  )
}
