'use client' import { ChevronsUpDownIcon, XIcon } from 'lucide-react' import { useEffect, useRef, useState } from 'react' import type { RelationOption } from '@/components/campaign/shared/RelationMultiSelect' import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/Avatar' import { Badge } from '@/components/ui/Badge' import { Button } from '@/components/ui/button' import { Command, CommandDialog, CommandGroup, CommandInput, CommandItem, CommandList, } from '@/components/ui/Command' import { Spinner } from '@/components/ui/Spinner' import { campaignUserInitials } from '@/utilities/campaignUserProfile' export type DemandResponsibleOption = RelationOption & { avatarUrl?: string | null } type DemandResponsibleMultiSelectProps = { /** FormData field name — repeated hidden inputs, one per selected id. */ name: string value: DemandResponsibleOption[] /** When set, this id renders as "(criador)" (informational marker). */ creatorUserId?: number | null /** Create flow: the creator chip cannot be removed (the hook re-adds it). */ lockCreator?: boolean /** Server action — short queries return municipality-advisor suggestions. */ search: (query: string) => Promise /** Trigger text while empty, e.g. "Buscar assessor…". */ triggerPlaceholder: string /** Accessible name of the add trigger (the list renders its own sr-only names). */ triggerAriaLabel: string disabled?: boolean /** Fires on every change with the full selected id list (dirty tracking). */ onChange?: (ids: number[]) => void } /** * C143 — multi-value responsible picker for campaign demands (staff only). * The chips carry the selected list as repeated hidden inputs; the search * catalog is the `searchDemandResponsibleOptions` action, whose short-query * branch returns the municipality's advisors as suggestions (a fill-in * shortcut — visibility comes only from the saved list). */ export const DemandResponsibleMultiSelect = ({ name, value, creatorUserId = null, lockCreator = true, search, triggerPlaceholder, triggerAriaLabel, disabled, onChange, }: DemandResponsibleMultiSelectProps) => { const [selected, setSelected] = useState(value) const [open, setOpen] = useState(false) const [query, setQuery] = useState('') const [options, setOptions] = useState([]) const [loading, setLoading] = useState(false) const [failed, setFailed] = useState(false) const requestId = useRef(0) const searchRef = useRef(search) searchRef.current = search useEffect(() => { if (!open) return const currentRequestId = ++requestId.current const timeout = window.setTimeout(() => { setLoading(true) setFailed(false) void searchRef .current(query.trim()) .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]) const isCreator = (id: number) => creatorUserId != null && creatorUserId === id const selectedIds = new Set(selected.map((option) => option.id)) // Discrete user events re-render between calls, so reading `selected` here // is safe (same shape as `RelationMultiSelect`); an updater side effect // would double-fire onChange under StrictMode. const add = (option: RelationOption) => { if (selectedIds.has(option.id)) return const next = [...selected, { ...option, avatarUrl: undefined }] setSelected(next) onChange?.(next.map((entry) => entry.id)) } const remove = (option: DemandResponsibleOption) => { if (isCreator(option.id) && lockCreator) return const next = selected.filter((entry) => entry.id !== option.id) setSelected(next) onChange?.(next.map((entry) => entry.id)) } const visibleOptions = options.filter((option) => !selectedIds.has(option.id)) const shortQuery = query.trim().length < 2 const selectedLabel = selected.length === 0 ? triggerPlaceholder : `${selected.length} ${selected.length === 1 ? 'responsável' : 'responsáveis'}` return ( <> {selected.length ? (
    {selected.map((option) => (
  • {option.avatarUrl ? ( {campaignUserInitials(option.name)} ) : null} {option.name} {isCreator(option.id) ? ( (criador) ) : null} {!isCreator(option.id) ? ( ) : null}
  • ))}
) : null} {loading ? (
) : failed ? (

Não foi possível concluir a busca.

) : visibleOptions.length > 0 ? ( {visibleOptions.map((option) => ( add(option)} > {option.name} ))} ) : (

{shortQuery ? 'Sem assessores sugeridos para este município.' : 'Nenhum resultado encontrado.'}

)}
) }