// Location picker widget for @rjsf forms.
// Fetches inventory locations from the API and renders a <select> dropdown
// showing "code -- name" for each location.

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

export function LocationPicker(props: WidgetProps) {
  const { id, value, required, disabled, readonly, onChange } = props
  const [locations, setLocations] = useState<Location[]>([])

  useEffect(() => {
    inventory.listLocations().then(setLocations).catch(() => setLocations([]))
  }, [])

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