saas_app/src/packages/administrativo/components/TCensecQualidade/TCensecQualidadeSelect.tsx

92 lines
3.1 KiB
TypeScript

'use client';
import React from 'react';
import { Button } from '@/components/ui/button';
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from '@/components/ui/command';
import { FormControl } from '@/components/ui/form';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { CheckIcon, ChevronsUpDownIcon } from 'lucide-react';
import GetCapitalize from '@/shared/actions/text/GetCapitalize';
import { useTCensecQualidadeIndexHook } from '../../hooks/TCensecQualidade/useTCensecQualidadeIndexHook';
export default function TCensecQualidadeSelect({ field }: any) {
const [open, setOpen] = React.useState(false);
const [isLoading, setIsLoading] = React.useState(false);
const { tCensecQualidade, indexTCensecQualidade } = useTCensecQualidadeIndexHook();
// Busca os dados uma única vez ao montar
React.useEffect(() => {
const loadData = async () => {
if (!tCensecQualidade.length) {
setIsLoading(true);
await indexTCensecQualidade();
setIsLoading(false);
}
};
loadData();
}, []);
const selected = tCensecQualidade.find(
(item) => String(item.censec_qualidade_id) === String(field.value),
);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<FormControl className="w-full">
<Button
variant="outline"
role="combobox"
aria-expanded={open}
disabled={isLoading}
className="justify-between"
>
{isLoading
? 'Carregando...'
: selected
? GetCapitalize(selected.descricao)
: 'Selecione...'}
<ChevronsUpDownIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent className="w-full p-0">
<Command>
<CommandInput placeholder="Buscar tipo logradouro..." />
<CommandList>
<CommandEmpty>
{isLoading ? 'Carregando...' : 'Nenhum resultado encontrado.'}
</CommandEmpty>
<CommandGroup>
{tCensecQualidade?.map((item) => (
<CommandItem
key={item.censec_qualidade_id}
value={item.descricao?.toLowerCase() ?? ''}
onSelect={() => {
field.onChange(Number(item.censec_qualidade_id));
setOpen(false);
}}
>
<CheckIcon
className={cn(
'mr-2 h-4 w-4',
String(field.value) === String(item.censec_qualidade_id)
? 'opacity-100'
: 'opacity-0',
)}
/>
{GetCapitalize(item.descricao)}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}