// Partner picker widget for @rjsf forms.
// Fetches partners from the API and renders a <select> dropdown
// showing "code -- name" for each partner.

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

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

  useEffect(() => {
    partners.list().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((p) => (
        <option key={p.id} value={p.code}>
          {p.code} — {p.name}
        </option>
      ))}
    </select>
  )
}
