'use client' import { useEffect, useState } from 'react' import { Combobox, ComboboxContent, ComboboxEmpty, ComboboxInput, ComboboxItem, ComboboxList, } from '@/components/ui/combobox' import { cn } from '@/lib/utils' import { matchesAtWordStart, normalizeSearchPhrase } from '@/lib/wordStartFilter' import type { StrictComboboxOption } from '@/utilities/territory/territoryComboboxOptions' type StrictComboboxProps = { id: string options: StrictComboboxOption[] value: string onValueChange: (value: string) => void onInvalid?: () => void error?: string placeholder?: string className?: string } export const StrictCombobox = ({ id, options, value, onValueChange, onInvalid, error, placeholder, className, }: StrictComboboxProps) => { const selected = options.find((option) => option.value === value) ?? null const [inputValue, setInputValue] = useState(selected?.label ?? '') useEffect(() => { setInputValue(selected?.label ?? '') }, [selected?.label]) return ( items={options} value={selected} inputValue={inputValue} onInputValueChange={setInputValue} onValueChange={(option) => { setInputValue(option?.label ?? '') onValueChange(option?.value ?? '') }} filter={(option, query) => matchesAtWordStart(option.label, query)} isItemEqualToValue={(left, right) => left?.value === right?.value} > { const normalized = normalizeSearchPhrase(event.currentTarget.value) const exact = options.find((option) => normalizeSearchPhrase(option.label) === normalized) if (normalized && !exact) { setInputValue('') onValueChange('') onInvalid?.() } else if (exact) { setInputValue(exact.label) onValueChange(exact.value) } else { setInputValue('') onValueChange('') } }} /> Nenhuma opção encontrada. {(option: StrictComboboxOption) => ( {option.label} )} ) }