'use client' import Link from 'next/link' import { useRouter } from 'next/navigation' import { useEffect, useId, useRef, useState, type ReactNode } from 'react' import type { MunicipalityListEngagementLevelResponse } from '@/app/(campaign)/campanha/(app)/municipios/engagement-level/types' import type { MunicipalityListPoliticalTrendResponse } from '@/app/(campaign)/campanha/(app)/municipios/political-trend/types' import { MunicipalityV2StatusReasonDialog } from '@/components/campaign/municipality/MunicipalityV2StatusReasonDialog' import { CampaignHoverTooltip } from '@/components/campaign/shared/CampaignHoverTooltip' import { Badge } from '@/components/ui/Badge' import { Field, FieldLabel } from '@/components/ui/field' import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select' import { campaignHoverExplanationClassName } from '@/lib/campaignHoverTooltip' import { campaignConceptHref, campaignConceptOneLiner } from '@/lib/campaignIntelligenceConcepts' import { postCampaignJson } from '@/lib/campaignJsonRequest' import { EMPTY_ENGAGEMENT_LEVEL_LABEL, ENGAGEMENT_LEVEL_RULES, engagementLevelRank, engagementLevels, formatEngagementLevelLabel, getEngagementLevelViolations, isEngagementLevel, type EngagementLevel, type EngagementLevelViolation, } from '@/lib/engagementLevel' import { parsePoliticalTrendStatusFormValue, politicalTrendStatuses, } from '@/lib/schemas/municipality' import { MUNICIPALITY_UPDATE_BODY_REQUIRED_MESSAGE, municipalityUpdatePolarityLabels, type MunicipalityUpdatePolarity, } from '@/lib/schemas/municipalityUpdate' import { cn } from '@/lib/utils' import type { CampaignFormActionState } from '@/utilities/campaignFormActionError' import { formatTerritorialClassWhy, politicalTrendLabels, territorialClassBadgeVariant, territorialClassLabels, } from '@/utilities/municipality/municipalityLabels' import { formatMunicipalitySignalAgeLabel } from '@/utilities/municipality/municipalitySignal' import { buildMunicipalityV2StatusAggregate, MUNICIPALITY_V2_SIGNAL_COLD_VALUE, resolveMunicipalityV2UpdateState, type MunicipalityV2StatusViewModel, } from '@/utilities/municipality/municipalityV2StatusView' const ENGAGEMENT_LEVEL_ENDPOINT = '/campanha/municipios/engagement-level' const POLITICAL_TREND_ENDPOINT = '/campanha/municipios/political-trend' const LEVEL_ERROR = 'Não foi possível registrar o nível. Tente novamente.' const TREND_ERROR = 'Não foi possível salvar a tendência. Tente novamente.' const UPDATE_ERROR = 'Não foi possível registrar a atualização. Tente novamente.' type PendingAxis = 'level' | 'trend' | 'update' | null type MunicipalityV2StatusStripProps = { status: MunicipalityV2StatusViewModel signalFormAction: (formData: FormData) => Promise } const ConceptTooltip = ({ conceptId, label, children, }: { conceptId: 'nivel-de-envolvimento' | 'classe-territorial' | 'pauta-do-silencio' label: string children: ReactNode }) => (

{campaignConceptOneLiner(conceptId)}

Ver em Conceitos } >
) const polarityOptions: readonly MunicipalityUpdatePolarity[] = ['boa', 'neutra', 'ruim'] export const MunicipalityV2StatusStrip = ({ status, signalFormAction, }: MunicipalityV2StatusStripProps) => { const router = useRouter() const formId = useId() const abortRef = useRef(null) const [level, setLevel] = useState(status.engagementLevel) const [levelNote, setLevelNote] = useState(status.levelNote) const [levelChangedAt, setLevelChangedAt] = useState(status.levelChangedAt) const [trendStatus, setTrendStatus] = useState(status.politicalTrendStatus) const [trendNote, setTrendNote] = useState(status.politicalTrendNote) const [polarity, setPolarity] = useState(status.lastUpdatePolarity) const [updateBody, setUpdateBody] = useState(status.lastUpdateBody) const [lastSignalAt, setLastSignalAt] = useState(status.lastSignalAt) const [pendingAxis, setPendingAxis] = useState(null) const [draftLevel, setDraftLevel] = useState(null) const [draftTrend, setDraftTrend] = useState(null) const [draftPolarity, setDraftPolarity] = useState(null) const [serverBlock, setServerBlock] = useState(null) const [errorMessage, setErrorMessage] = useState(null) const [isPending, setIsPending] = useState(false) useEffect(() => () => abortRef.current?.abort(), []) // Adopt RSC refresh values when the server revalidates after a write. useEffect(() => { setLevel(status.engagementLevel) setLevelNote(status.levelNote) setLevelChangedAt(status.levelChangedAt) setTrendStatus(status.politicalTrendStatus) setTrendNote(status.politicalTrendNote) setPolarity(status.lastUpdatePolarity) setUpdateBody(status.lastUpdateBody) setLastSignalAt(status.lastSignalAt) }, [status]) const updateSelect = resolveMunicipalityV2UpdateState({ polarity, lastSignalAt, }) const aggregate = buildMunicipalityV2StatusAggregate({ levelNote, trendNote, updateBody, updatePolarity: polarity, lastSignalAt, engagementLevel: level, }) const levelViolations = pendingAxis === 'level' && draftLevel ? [ ...getEngagementLevelViolations({ from: level, to: draftLevel, levelChangedAt, now: new Date(), triangulatedShock: false, }), ...(serverBlock ?? []), ] : [] const uniqueLevelViolations = levelViolations.filter( (violation, index, list) => list.findIndex((item) => item.id === violation.id) === index, ) const isJump = pendingAxis === 'level' && draftLevel !== null && level !== null && Math.abs(engagementLevelRank[draftLevel] - engagementLevelRank[level]) > ENGAGEMENT_LEVEL_RULES.maxStepsWithoutShock const closeDialog = () => { setPendingAxis(null) setDraftLevel(null) setDraftTrend(null) setDraftPolarity(null) setServerBlock(null) setErrorMessage(null) } const confirmLevel = async (reason: string) => { if (!draftLevel || isPending) return const controller = new AbortController() abortRef.current = controller setIsPending(true) setErrorMessage(null) setServerBlock(null) try { const { payload } = await postCampaignJson( ENGAGEMENT_LEVEL_ENDPOINT, { municipalityId: status.id, level: draftLevel, note: reason.trim() ? reason.trim() : null, triangulatedShock: false, override: false, }, controller.signal, ) if (payload.status === 'success') { setLevel(payload.savedLevel.level) setLevelNote(payload.savedLevel.note) setLevelChangedAt(payload.savedLevel.changedAt) closeDialog() router.refresh() return } if (payload.status === 'blocked') { setServerBlock(payload.violations) return } setErrorMessage(payload.message || LEVEL_ERROR) } catch { if (controller.signal.aborted) return setErrorMessage(LEVEL_ERROR) } finally { setIsPending(false) } } const confirmTrend = async (reason: string) => { if (pendingAxis !== 'trend' || isPending) return const controller = new AbortController() abortRef.current = controller setIsPending(true) setErrorMessage(null) try { const { payload } = await postCampaignJson( POLITICAL_TREND_ENDPOINT, { municipalityId: status.id, status: draftTrend, note: reason.trim() ? reason.trim() : null, }, controller.signal, ) if (payload.status === 'success') { setTrendStatus(payload.savedTrend.status) setTrendNote(payload.savedTrend.note) closeDialog() router.refresh() return } setErrorMessage(payload.message || TREND_ERROR) } catch { if (controller.signal.aborted) return setErrorMessage(TREND_ERROR) } finally { setIsPending(false) } } const confirmUpdate = async (reason: string) => { if (!draftPolarity || isPending) return const body = reason.trim() if (!body) { setErrorMessage(MUNICIPALITY_UPDATE_BODY_REQUIRED_MESSAGE) return } setIsPending(true) setErrorMessage(null) try { const formData = new FormData() formData.set('municipalityId', String(status.id)) formData.set('polarity', draftPolarity) formData.set('body', body) formData.set('urgent', 'false') formData.set('adversarySignal', 'false') const result = await signalFormAction(formData) if (result.status !== 'success') { setErrorMessage(result.message || UPDATE_ERROR) return } setPolarity(draftPolarity) setUpdateBody(reason.trim() ? reason.trim() : null) setLastSignalAt(new Date().toISOString()) closeDialog() router.refresh() } catch { setErrorMessage(UPDATE_ERROR) } finally { setIsPending(false) } } const dialogTitle = pendingAxis === 'level' ? 'Confirmar nível de envolvimento' : pendingAxis === 'trend' ? 'Confirmar tendência' : pendingAxis === 'update' ? 'Confirmar atualização' : '' const dialogDescription = pendingAxis === 'level' && draftLevel ? formatEngagementLevelLabel(draftLevel) : pendingAxis === 'trend' ? draftTrend ? politicalTrendLabels[draftTrend] : 'Não registrada' : pendingAxis === 'update' && draftPolarity ? municipalityUpdatePolarityLabels[draftPolarity] : '' return (

Status

Nível {status.canMoveEngagementLevel ? ( { const next = event.target.value if (!isEngagementLevel(next) || next === level) { event.target.value = level ?? '' return } setDraftLevel(next) setPendingAxis('level') setServerBlock(null) setErrorMessage(null) }} > {EMPTY_ENGAGEMENT_LEVEL_LABEL} {engagementLevels.map((option) => ( {formatEngagementLevelLabel(option)} ))} ) : (

{level ? formatEngagementLevelLabel(level) : EMPTY_ENGAGEMENT_LEVEL_LABEL}

)}
Tendência { const next = parsePoliticalTrendStatusFormValue(event.target.value) if (next === trendStatus) return setDraftTrend(next) setPendingAxis('trend') setErrorMessage(null) }} > Não registrada {politicalTrendStatuses.map((option) => ( {politicalTrendLabels[option]} ))} Polaridade { const raw = event.target.value if (raw === MUNICIPALITY_V2_SIGNAL_COLD_VALUE) { event.target.value = updateSelect.value return } const next = raw as MunicipalityUpdatePolarity if (!next || next === polarity) { event.target.value = updateSelect.value return } setDraftPolarity(next) setPendingAxis('update') setErrorMessage(null) }} > {updateSelect.isCold ? ( {updateSelect.label} ) : null} {polarityOptions.map((option) => ( {municipalityUpdatePolarityLabels[option]} ))}
Classe
{territorialClassLabels[status.territorialClass.class]} {formatMunicipalitySignalAgeLabel(updateSelect.ageInDays)}

{formatTerritorialClassWhy(status.territorialClass.factors)}

{aggregate}

{ if (!open) { closeDialog() } }} title={dialogTitle} description={dialogDescription} isPending={isPending} errorMessage={errorMessage} showTriangulatedShock={Boolean(isJump)} triangulatedShock={false} onTriangulatedShockChange={() => {}} violations={uniqueLevelViolations} override={false} onOverrideChange={() => {}} onConfirm={(reason) => { if (pendingAxis === 'level') void confirmLevel(reason) else if (pendingAxis === 'trend') void confirmTrend(reason) else if (pendingAxis === 'update') void confirmUpdate(reason) }} />
) }