import { useEffect, useMemo, useState } from 'react'

export function ExpenseVendorFields({
  retailors,
  initialRetailor,
  inputName = 'retailor',
  selectId = 'retailor_select',
  inputId = 'retailor_input',
}: {
  retailors: string[]
  initialRetailor: string
  inputName?: string
  selectId?: string
  inputId?: string
}) {
  const list = useMemo(() => (Array.isArray(retailors) ? retailors : []).filter(Boolean), [retailors])
  const [selectVal, setSelectVal] = useState<string>('')
  const [inputVal, setInputVal] = useState(initialRetailor)

  useEffect(() => {
    const cur = String(initialRetailor ?? '').trim()
    setInputVal(initialRetailor ?? '')
    if (!cur) {
      setSelectVal('')
      return
    }
    if (list.includes(cur)) setSelectVal(cur)
    else setSelectVal('_other')
  }, [initialRetailor, list])

  function onSelectChange(val: string) {
    setSelectVal(val)
    if (val === '_other') return
    if (val === '') return
    setInputVal(val)
  }

  const pickedFromList = selectVal !== '' && selectVal !== '_other'

  return (
    <>
      <select
        id={selectId}
        className="form-control form-select"
        value={selectVal}
        onChange={(e) => onSelectChange(e.target.value)}
      >
        <option value="">-- Select Vendor --</option>
        {list.map((r) => (
          <option key={r} value={r}>
            {r}
          </option>
        ))}
        <option value="_other">Other</option>
      </select>
      {pickedFromList ? (
        <input type="hidden" name={inputName} value={inputVal} />
      ) : (
        <input
          type="text"
          id={inputId}
          name={inputName}
          className="form-control mt-2"
          placeholder="Enter vendor"
          value={inputVal}
          onChange={(e) => setInputVal(e.target.value)}
          autoComplete="off"
        />
      )}
    </>
  )
}
