'use client' import { ChevronsUpDownIcon } from 'lucide-react' import { useEffect, useState } from 'react' import { Button } from '@/components/ui/button' import { Command, CommandDialog, CommandGroup, CommandInput, CommandItem, CommandList, } from '@/components/ui/Command' import { Spinner } from '@/components/ui/Spinner' import { useAsyncSearchOptions } from '@/hooks/useAsyncSearchOptions' export type AsyncSearchOption = { id: number label: string } type AsyncSearchComboboxProps = { name?: string label: string value: AsyncSearchOption | null onChange?: (option: AsyncSearchOption | null) => void search: (query: string) => Promise emptyOptionLabel?: string dialogDescription?: string isQueryReady?: (query: string) => boolean queryTooShortMessage?: string pinnedOptions?: AsyncSearchOption[] pinnedGroupHeading?: string } export const AsyncSearchCombobox = ({ name, label, value, onChange, search, emptyOptionLabel = 'Nenhum', dialogDescription = 'Digite para buscar.', isQueryReady = () => true, queryTooShortMessage = 'Digite para buscar.', pinnedOptions = [], pinnedGroupHeading = 'Sugestões', }: AsyncSearchComboboxProps) => { const [open, setOpen] = useState(false) const [query, setQuery] = useState('') const [selected, setSelected] = useState(value) const { options, loading, failed } = useAsyncSearchOptions({ open, query, search, isQueryReady }) useEffect(() => { setSelected(value) }, [value]) const choose = (option: AsyncSearchOption | null) => { setSelected(option) setOpen(false) setQuery('') onChange?.(option) } const visibleOptions = options.filter((option) => option.id !== selected?.id) const visiblePinned = pinnedOptions.filter((option) => option.id !== selected?.id) return ( <> {name ? : null} {loading ? (
) : failed ? (

Não foi possível concluir a busca.

) : ( <> choose(null)}> {emptyOptionLabel} {selected ? ( choose(selected)} > {selected.label} ) : null} {visiblePinned.length ? ( {visiblePinned.map((option) => ( choose(option)} > {option.label} ))} ) : null} {visibleOptions.length ? ( {visibleOptions.map((option) => ( choose(option)} > {option.label} ))} ) : (

{!isQueryReady(query) ? queryTooShortMessage : 'Nenhum resultado encontrado.'}

)} )}
) }