'use client' import { useEffect, useRef, useState } from 'react' import { ChevronsUpDownIcon } from 'lucide-react' import { Button } from '@/components/ui/button' import { Command, CommandDialog, CommandGroup, CommandInput, CommandItem, CommandList, } from '@/components/ui/Command' import { Spinner } from '@/components/ui/Spinner' export type ContactComboboxOption = { id: number name: string phone: string } type ContactComboboxProps = { name?: string label: string current: ContactComboboxOption | null search: (query: string) => Promise emptyOptionLabel?: string onChange?: (contact: ContactComboboxOption | null) => void } const contactLabel = (contact: ContactComboboxOption | null, emptyLabel: string): string => contact ? `${contact.name} · ${contact.phone}` : emptyLabel export const ContactCombobox = ({ name, label, current, search, emptyOptionLabel = 'Nenhum responsável', onChange, }: ContactComboboxProps) => { const [open, setOpen] = useState(false) const [query, setQuery] = useState('') const [selected, setSelected] = useState(current) const [options, setOptions] = useState([]) const [loading, setLoading] = useState(false) const [failed, setFailed] = useState(false) const requestId = useRef(0) useEffect(() => { if (!open) return const currentRequestId = ++requestId.current const timeout = window.setTimeout(() => { setLoading(true) setFailed(false) void search(query) .then((nextOptions) => { if (requestId.current !== currentRequestId) return setOptions(nextOptions) }) .catch(() => { if (requestId.current !== currentRequestId) return setFailed(true) }) .finally(() => { if (requestId.current === currentRequestId) setLoading(false) }) }, 250) return () => window.clearTimeout(timeout) }, [open, query, search]) const choose = (contact: ContactComboboxOption | null) => { setSelected(contact) setOpen(false) setQuery('') onChange?.(contact) } const visibleOptions = options.filter((option) => option.id !== selected?.id) return ( <> {name ? : null} {loading ? (
) : failed ? (

Não foi possível buscar contatos.

) : ( <> choose(null)}> {emptyOptionLabel} {selected ? ( choose(selected)} > {contactLabel(selected, emptyOptionLabel)} ) : null} {visibleOptions.length ? ( {visibleOptions.map((contact) => ( choose(contact)} > {contactLabel(contact, emptyOptionLabel)} ))} ) : (

Nenhum contato encontrado.

)} )}
) }