'use client'
import { CircleHelpIcon, MinusIcon, TrendingDownIcon, TrendingUpIcon } from 'lucide-react'
import { useEffect, useMemo, useState, type ReactNode } from 'react'
import type {
MunicipalityListPoliticalTrendResponse,
MunicipalityListSavedPoliticalTrend,
} from '@/app/(campaign)/campanha/(app)/municipios/political-trend/types'
import {
CampaignCellEditOverlay,
type CampaignCellEditOverlayVariant,
} from '@/components/campaign/shared/CampaignCellEditOverlay'
import { useCampaignCellAutosave } from '@/components/campaign/shared/useCampaignCellAutosave'
import { Alert, AlertDescription } from '@/components/ui/Alert'
import { Badge } from '@/components/ui/Badge'
import { Field, FieldLabel } from '@/components/ui/field'
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
import { Spinner } from '@/components/ui/Spinner'
import { Textarea } from '@/components/ui/textarea'
import { parsePoliticalTrendStatusFormValue } from '@/lib/schemas/municipality'
import {
politicalTrendBadgeVariant,
politicalTrendLabels,
} from '@/utilities/municipality/municipalityLabels'
const NOTE_AUTOSAVE_MS = 600
const STATUS_AUTOSAVE_MS = 150
const POLITICAL_TREND_ENDPOINT = '/campanha/municipios/political-trend'
const SAVE_ERROR_MESSAGE = 'Não foi possível salvar a tendência. Tente novamente.'
const NOTE_MAX_LENGTH = 2000
const normalizeNote = (note: string | null | undefined): string | null => {
const trimmed = note?.trim()
return trimmed ? trimmed : null
}
const trendsEqual = (
left: MunicipalityListSavedPoliticalTrend,
right: MunicipalityListSavedPoliticalTrend,
): boolean => left.status === right.status && normalizeNote(left.note) === normalizeNote(right.note)
type MunicipalityListTrendControlProps = {
municipalityID: number
municipalityName: string
status: MunicipalityListSavedPoliticalTrend['status']
trendNote: string | null
variant: CampaignCellEditOverlayVariant
triggerPresentation?: 'full' | 'compact' | 'adaptive'
/**
* B193 — replaces the internal trend badge trigger (e.g. the dense mobile
* card's "Tendência" chip). Receives the LIVE autosave trend.
*/
trigger?: (trend: MunicipalityListSavedPoliticalTrend) => ReactNode
/** B193 — dense card chip styling override (shorter, pill-shaped). */
triggerClassName?: string
}
const politicalTrendIcon = {
favoravel: TrendingUpIcon,
neutra: MinusIcon,
desfavoravel: TrendingDownIcon,
} as const
export const MunicipalityListTrendControl = ({
municipalityID,
municipalityName,
status,
trendNote,
variant,
triggerPresentation = 'full',
trigger,
triggerClassName,
}: MunicipalityListTrendControlProps) => {
const { open, onOpenChange, value, change, flush, isPending, errorMessage, statusMessage } =
useCampaignCellAutosave<
MunicipalityListSavedPoliticalTrend,
MunicipalityListPoliticalTrendResponse
>({
// Memoized because the hook's server-adoption effect keys on this
// reference; a fresh literal per render would run it (harmlessly, since
// `equals` guards the body) on every commit of the list.
value: useMemo(() => ({ status, note: normalizeNote(trendNote) }), [status, trendNote]),
equals: trendsEqual,
endpoint: POLITICAL_TREND_ENDPOINT,
buildBody: (trend) => ({
municipalityId: municipalityID,
status: trend.status,
note: trend.note,
}),
readSaved: (payload) => payload.savedTrend,
errorMessage: SAVE_ERROR_MESSAGE,
pendingMessage: 'Salvando tendência.',
})
// The only state the hook cannot hold: the textarea's raw text, which the
// saved note is the trimmed form of. It follows the saved note whenever that
// changes for a reason other than this typing (adoption, revert, server echo)
// and is left alone while the two still agree, so trailing spaces survive.
const [noteDraft, setNoteDraft] = useState(trendNote ?? '')
useEffect(() => {
setNoteDraft((current) =>
normalizeNote(current) === value.note ? current : (value.note ?? ''),
)
}, [value.note])
const hasNote = Boolean(value.note)
const trendLabel = value.status ? politicalTrendLabels[value.status] : 'Não registrada'
const TrendIcon = value.status ? politicalTrendIcon[value.status] : CircleHelpIcon
const badgeVariant = value.status ? politicalTrendBadgeVariant[value.status] : 'outline'
const fullTrigger =