'use client' import { MessageCircleIcon, PencilIcon, PlusIcon, SaveIcon, SearchXIcon, UserCogIcon, XIcon, } from 'lucide-react' import Link from 'next/link' import { useRouter } from 'next/navigation' import { useState, useTransition } from 'react' import { toast } from 'sonner' import { AdvisorDebouncedTextCell } from '@/components/campaign/AdvisorDebouncedTextCell' import { AdvisorMunicipalityCell } from '@/components/campaign/AdvisorMunicipalityCell' import { AdvisorPasswordResetButton } from '@/components/campaign/AdvisorPasswordResetButton' import { CampaignListEmptyState } from '@/components/campaign/CampaignListEmptyState' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Spinner } from '@/components/ui/Spinner' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from '@/components/ui/Table' import type { AdvisorMunicipalityIndexEntry } from '@/lib/advisorMunicipalityPortfolio' import { isPlanilhaPlaceholderEmail } from '@/lib/schemas/advisor' import { cn } from '@/lib/utils' import type { AdvisorRowViewModel } from '@/utilities/advisorData' import type { CampaignFormActionState } from '@/utilities/campaignFormActionError' import { formatBrazilianPhoneInput, normalizeBrazilianPhone, sanitizeBrazilianPhoneInput, buildWhatsAppUrl, } from '@/utilities/phone' type MunicipalityRef = { id: number; name: string; slug: string } type DraftAdvisor = { name: string email: string phone: string municipalities: MunicipalityRef[] } type AdvisorsTableProps = { rows: AdvisorRowViewModel[] municipalityIndex: AdvisorMunicipalityIndexEntry[] hasQuery: boolean updateProfileAction: ( state: CampaignFormActionState, formData: FormData, ) => Promise membershipAction: ( state: CampaignFormActionState, formData: FormData, ) => Promise batchAction: ( state: CampaignFormActionState, formData: FormData, ) => Promise createAction: ( state: CampaignFormActionState, formData: FormData, ) => Promise passwordResetAction: ( state: CampaignFormActionState, formData: FormData, ) => Promise } const emptyDraft = (): DraftAdvisor => ({ name: '', email: '', phone: '', municipalities: [], }) const whatsAppHrefForPhone = (phone: string | null): string | null => { if (!phone || !normalizeBrazilianPhone(phone)) return null try { return buildWhatsAppUrl(phone) } catch { return null } } const copyText = async (label: string, value: string) => { try { await navigator.clipboard.writeText(value) toast.success(`${label} copiado.`) } catch { toast.error(`Não foi possível copiar o ${label.toLowerCase()}.`) } } /** Mirrors the inline input box (height, border, padding) so toggling edition never reflows. */ const READ_CELL_CLASS = 'flex min-h-10 w-full items-center rounded-full border border-transparent px-2 text-left' const displayEmail = (email: string | null): string => { if (!email || isPlanilhaPlaceholderEmail(email)) return '' return email } export const AdvisorsTable = ({ rows, municipalityIndex, hasQuery, updateProfileAction, membershipAction, batchAction, createAction, passwordResetAction, }: AdvisorsTableProps) => { const router = useRouter() const [editing, setEditing] = useState(false) const [draft, setDraft] = useState(null) const [isCreating, startCreate] = useTransition() const refresh = () => router.refresh() const startDraft = () => { setEditing(true) setDraft(emptyDraft()) } const cancelDraft = () => setDraft(null) const leaveEditing = () => { setDraft(null) setEditing(false) } const saveDraft = () => { if (!draft) return if (draft.name.trim().length < 2) { toast.error('Informe o nome do assessor.') return } if (!draft.email.trim()) { toast.error('Informe o e-mail do assessor.') return } const formData = new FormData() formData.set('name', draft.name.trim()) formData.set('email', draft.email.trim()) if (draft.phone.trim()) formData.set('phone', draft.phone.trim()) for (const municipality of draft.municipalities) { formData.append('municipalityIds', String(municipality.id)) } startCreate(async () => { const result = await createAction({}, formData) if (result.status === 'success') { toast.success(result.message ?? 'Assessor criado.') setDraft(null) refresh() return } toast.error(result.message ?? 'Não foi possível criar o assessor.') }) } const showEmpty = rows.length === 0 && !draft return (
{editing ? ( ) : ( )}
{showEmpty ? ( {!hasQuery ? ( ) : null} ) : (
Nome E-mail Celular Municípios Ações {draft ? ( { const name = event.currentTarget.value setDraft((current) => (current ? { ...current, name } : current)) }} placeholder="Nome" aria-label="Nome do novo assessor" className="min-h-10 border-transparent bg-transparent px-2 shadow-none hover:border-input focus-visible:border-input" autoFocus /> { const email = event.currentTarget.value setDraft((current) => (current ? { ...current, email } : current)) }} placeholder="E-mail" aria-label="E-mail do novo assessor" className="min-h-10 border-transparent bg-transparent px-2 shadow-none hover:border-input focus-visible:border-input" /> { const phone = formatBrazilianPhoneInput( sanitizeBrazilianPhoneInput(event.currentTarget.value), ) setDraft((current) => (current ? { ...current, phone } : current)) }} placeholder="Celular" aria-label="Celular do novo assessor" className="min-h-10 border-transparent bg-transparent px-2 shadow-none hover:border-input focus-visible:border-input" /> setDraft((current) => (current ? { ...current, municipalities } : current)) } membershipAction={membershipAction} batchAction={batchAction} />
) : null} {rows.map((row) => { const whatsAppHref = whatsAppHrefForPhone(row.phone) const emailShown = displayEmail(row.email) const phoneShown = row.phone ? formatBrazilianPhoneInput(row.phone) : '' return ( {editing ? ( ) : ( {row.name} )} {editing ? ( ) : emailShown ? ( ) : ( — )} {editing ? ( ) : phoneShown ? ( ) : ( — )}
{whatsAppHref ? ( ) : ( )}
) })}
)}
) }