'use client' import { CheckIcon, InfoIcon, PlusIcon, TriangleAlertIcon } from 'lucide-react' import { useRouter } from 'next/navigation' import { useActionState, useCallback, useEffect, useMemo, useRef, useState, useTransition, } from 'react' import { toast } from 'sonner' import { declareVotesWizardFormAction } from '@/app/(campaign)/campanha/(app)/acoes/wizardLeadershipFormActions' import type { LeadershipListSupportStatusResponse } from '@/app/(campaign)/campanha/(app)/liderancas/support-status/types' import { SupportStatusBadge } from '@/components/campaign/leadership/SupportStatusBadge' import { WizardLeadershipForm } from '@/components/campaign/leadership/WizardLeadershipForm' import { CampaignFormActionMessage } from '@/components/campaign/shared/CampaignFormActionMessage' import { CampaignWizardNavLink } from '@/components/campaign/shared/CampaignWizardNavLink' import { CampaignWizardShell } from '@/components/campaign/shared/CampaignWizardShell' import { Alert, AlertDescription } from '@/components/ui/Alert' import { Badge } from '@/components/ui/Badge' import { Button } from '@/components/ui/button' import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle, } from '@/components/ui/Drawer' import { Field, FieldError, FieldLabel } from '@/components/ui/field' import { Input } from '@/components/ui/input' import { Spinner } from '@/components/ui/Spinner' import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip' import type { CampaignWizardActionId } from '@/lib/campaignActionRoutes' import { postCampaignJson } from '@/lib/campaignJsonRequest' import { recordLastActedMunicipality } from '@/lib/campaignLastActedMunicipality' import { WIZARD_LEADERSHIP_ADD_TILE_LABEL, WIZARD_LEADERSHIP_CONTINUE_LABEL, WIZARD_LEADERSHIP_DECLARE_VOTES_LABEL, WIZARD_LEADERSHIP_EMPTY_GRID, WIZARD_LEADERSHIP_EMPTY_NOTES, WIZARD_LEADERSHIP_FORM_CREATE_TITLE, WIZARD_LEADERSHIP_FORM_EDIT_TITLE, WIZARD_LEADERSHIP_SAVED_TOAST, WIZARD_LEADERSHIP_STATUS_DRAWER_TITLE, WIZARD_LEADERSHIP_STATUS_PENDING, WIZARD_LEADERSHIP_STATUS_SAVE_ERROR, WIZARD_LEADERSHIP_VOTES_DRAWER_TITLE, WIZARD_LEADERSHIP_VOTES_PENDING, WIZARD_LEADERSHIP_VOTES_SAVED, wizardFlowTitleForSlug, } from '@/lib/campaignWizardCopy' import { truncateNameAtWordBoundary } from '@/lib/leadershipNameTruncate' import { isSupportStatus, leadershipSupportStatuses, type SupportStatus, } from '@/lib/schemas/leadership' import { cn } from '@/lib/utils' import { WIZARD_THUMB_TILE_GRID_CLASS, WIZARD_THUMB_TILE_ITEM_CLASS, } from '@/lib/wizardThumbGrid' import { resolveWizardChainEntry, wizardChainContinueHref, wizardChainEndHref, } from '@/lib/wizardActionChain' import { WIZARD_LEADERSHIP_FORM_LAYER, wizardStepPreviousHref } from '@/lib/wizardBack' import { resolveWizardLeadershipSkip, type WizardLeadershipTileViewModel, } from '@/lib/wizardLeadershipContract' import { fieldError } from '@/utilities/campaignFormFields' import { supportStatusLabels } from '@/utilities/leadership/leadershipLabels' const SUPPORT_STATUS_ENDPOINT = '/campanha/liderancas/support-status' const DEFAULT_STATUS: SupportStatus = 'a_abordar' type WizardLeadershipStepProps = { actionSlug: string municipalityId: number municipalityName: string municipalitySlug: string entryAction?: CampaignWizardActionId initialTiles: WizardLeadershipTileViewModel[] initialLeadershipId?: number returnPath?: string } type WizardLeadershipMode = | { kind: 'grid' } | { kind: 'form'; leadership: WizardLeadershipTileViewModel | null } const notesLabel = (notes: string | null): string => notes?.trim() ? notes.trim() : WIZARD_LEADERSHIP_EMPTY_NOTES const secondaryContact = (tile: WizardLeadershipTileViewModel): string | null => tile.phone?.trim() || tile.email?.trim() || null const drawerContextLabel = ( tile: WizardLeadershipTileViewModel, municipalityName: string, ): string => `${tile.name} · ${municipalityName}` export const WizardLeadershipStep = ({ actionSlug, municipalityId, municipalityName, municipalitySlug, entryAction, initialTiles, initialLeadershipId, returnPath, }: WizardLeadershipStepProps) => { const router = useRouter() const [isContinuing, startContinueTransition] = useTransition() const initialMode = useMemo((): WizardLeadershipMode => { if (initialLeadershipId === undefined) { return { kind: 'grid' } } const leadership = initialTiles.find((tile) => tile.id === initialLeadershipId) return leadership ? { kind: 'form', leadership } : { kind: 'grid' } }, [initialLeadershipId, initialTiles]) const [mode, setMode] = useState(initialMode) const [dirty, setDirty] = useState(false) const [tiles, setTiles] = useState(initialTiles) const [infoTile, setInfoTile] = useState(null) const [statusTile, setStatusTile] = useState(null) const [votesTile, setVotesTile] = useState(null) useEffect(() => { setTiles(initialTiles) }, [initialTiles]) const skipConfig = resolveWizardLeadershipSkip(entryAction, municipalitySlug, returnPath) const chainContinueHref = wizardChainContinueHref( resolveWizardChainEntry(entryAction, 'update-leadership'), 'update-leadership', municipalitySlug, returnPath, ) const stepTitle = mode.kind === 'form' ? mode.leadership ? WIZARD_LEADERSHIP_FORM_EDIT_TITLE : WIZARD_LEADERSHIP_FORM_CREATE_TITLE : null const trailingAction = skipConfig ? ( ) : undefined const markDirtyAndRefresh = useCallback(() => { recordLastActedMunicipality(municipalitySlug) setDirty(true) router.refresh() }, [municipalitySlug, router]) const handlePopFormLayer = useCallback(() => { setMode({ kind: 'grid' }) }, []) const handleSaved = useCallback(() => { markDirtyAndRefresh() setMode({ kind: 'grid' }) toast.success(WIZARD_LEADERSHIP_SAVED_TOAST) }, [markDirtyAndRefresh]) const handleStatusSaved = useCallback( (leadershipId: number, supportStatus: SupportStatus) => { setTiles((current) => current.map((tile) => (tile.id === leadershipId ? { ...tile, supportStatus } : tile)), ) setStatusTile(null) markDirtyAndRefresh() }, [markDirtyAndRefresh], ) const handleVotesSaved = useCallback( (leadershipId: number, declaredVotes: number) => { setTiles((current) => current.map((tile) => (tile.id === leadershipId ? { ...tile, declaredVotes } : tile)), ) setVotesTile(null) markDirtyAndRefresh() }, [markDirtyAndRefresh], ) const handleContinue = () => { startContinueTransition(() => { router.replace(chainContinueHref) }) } return ( {mode.kind === 'form' ? ( ) : (
{tiles.length === 0 ? (

{WIZARD_LEADERSHIP_EMPTY_GRID}

) : null}
    {tiles.map((tile) => (
  • setMode({ kind: 'form', leadership: tile })} onInfo={() => setInfoTile(tile)} onStatus={() => setStatusTile(tile)} onVotes={() => setVotesTile(tile)} />
  • ))}
)} {dirty && mode.kind === 'grid' ? (
) : null} !open && setInfoTile(null)}> {infoTile?.name ?? 'Observação'} Observação interna da liderança
{notesLabel(infoTile?.notes ?? null)}
setStatusTile(null)} onSaved={handleStatusSaved} /> setVotesTile(null)} onSaved={handleVotesSaved} />
) } type LeadershipTileButtonProps = { tile: WizardLeadershipTileViewModel onOpen: () => void onInfo: () => void onStatus: () => void onVotes: () => void } const LeadershipTileButton = ({ tile, onOpen, onInfo, onStatus, onVotes, }: LeadershipTileButtonProps) => { const secondary = secondaryContact(tile) const noteText = notesLabel(tile.notes) const status = tile.supportStatus ?? DEFAULT_STATUS const showDeclareVotesWarning = tile.declaredVotes === 0 return (
{noteText}
) } type WizardLeadershipStatusDrawerProps = { tile: WizardLeadershipTileViewModel | null municipalityName: string onClose: () => void onSaved: (leadershipId: number, supportStatus: SupportStatus) => void } const WizardLeadershipStatusDrawer = ({ tile, municipalityName, onClose, onSaved, }: WizardLeadershipStatusDrawerProps) => { const [pendingStatus, setPendingStatus] = useState(null) const [errorMessage, setErrorMessage] = useState(null) useEffect(() => { if (tile === null) { setPendingStatus(null) setErrorMessage(null) } }, [tile]) const currentStatus = tile?.supportStatus ?? DEFAULT_STATUS const handleSelect = async (nextStatus: SupportStatus) => { if (tile === null || nextStatus === currentStatus || pendingStatus !== null) return setPendingStatus(nextStatus) setErrorMessage(null) const { ok, payload } = await postCampaignJson( SUPPORT_STATUS_ENDPOINT, { leadershipId: tile.id, supportStatus: nextStatus }, ) if (!ok || payload.status !== 'success') { setPendingStatus(null) setErrorMessage( payload.status === 'error' ? payload.message : WIZARD_LEADERSHIP_STATUS_SAVE_ERROR, ) return } if (!isSupportStatus(payload.savedSupportStatus)) { setPendingStatus(null) setErrorMessage(WIZARD_LEADERSHIP_STATUS_SAVE_ERROR) return } onSaved(tile.id, payload.savedSupportStatus) setPendingStatus(null) } const statusMessage = errorMessage ? errorMessage : pendingStatus !== null ? WIZARD_LEADERSHIP_STATUS_PENDING : '' return ( !open && onClose()}> {WIZARD_LEADERSHIP_STATUS_DRAWER_TITLE} {tile ? drawerContextLabel(tile, municipalityName) : null}

{statusMessage}

    {leadershipSupportStatuses.map((option) => { const isCurrent = option === currentStatus const isPending = pendingStatus === option return (
  • ) })}
{errorMessage ? ( {errorMessage} ) : null}
) } type WizardLeadershipVotesDrawerProps = { tile: WizardLeadershipTileViewModel | null municipalityId: number municipalityName: string onClose: () => void onSaved: (leadershipId: number, declaredVotes: number) => void } const WizardLeadershipVotesDrawer = ({ tile, municipalityId, municipalityName, onClose, onSaved, }: WizardLeadershipVotesDrawerProps) => { const [state, submitAction, isPending] = useActionState(declareVotesWizardFormAction, {}) const [inputValue, setInputValue] = useState('') const handledMessageRef = useRef(undefined) useEffect(() => { if (tile !== null) { setInputValue(tile.declaredVotes > 0 ? String(tile.declaredVotes) : '') handledMessageRef.current = undefined } }, [tile]) useEffect(() => { if ( tile === null || !state.message || state.message === handledMessageRef.current || state.fieldErrors ) { return } if (state.message === WIZARD_LEADERSHIP_VOTES_SAVED) { handledMessageRef.current = state.message const parsed = Number.parseInt(inputValue, 10) if (!Number.isNaN(parsed)) { onSaved(tile.id, parsed) } } }, [inputValue, onSaved, state.fieldErrors, state.message, tile]) return ( !open && onClose()}> {WIZARD_LEADERSHIP_VOTES_DRAWER_TITLE} {tile ? drawerContextLabel(tile, municipalityName) : null}
{tile !== null ? : null}

{isPending ? WIZARD_LEADERSHIP_VOTES_PENDING : (state.message ?? '')}

Votos declarados setInputValue(event.target.value)} className="min-h-11" disabled={isPending} /> {fieldError(state.fieldErrors, 'declaredVotes') ? ( {fieldError(state.fieldErrors, 'declaredVotes')} ) : null}
) }