'use client' import { useRouter } from 'next/navigation' import { startTransition, useActionState, useEffect, useRef, useState, type FormEvent } from 'react' import { toast } from 'sonner' import { useContactCreate } from '@/components/campaign/contacts/ContactCreateState' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Spinner } from '@/components/ui/Spinner' import { CitiesByState } from '@/lib/cities' import { formatBrazilianPhoneInput, sanitizeBrazilianPhoneInput } from '@/lib/phone' import { cn } from '@/lib/utils' import type { CampaignFormActionState } from '@/utilities/campaignFormActionError' import { firstFormActionMessage } from '@/utilities/campaignFormFields' const stateOptions = Object.keys(CitiesByState) const rowInputClassName = 'border-border/60 bg-background shadow-none focus-visible:ring-1 focus-visible:ring-ring/50' type ContactCreateRowProps = { /** The `contatos/formActions` create ladder (`runCampaignFormAction`). */ formAction: ( state: CampaignFormActionState, formData: FormData, ) => Promise } /** * C139 — the create row of the contacts table: an empty ficha at the top of * the list (highlighted background, borderless inputs), mounted by the shared * create store (omnibox button / mobile FAB). Salvar stays disabled until the * name is filled; a conflict (duplicate name) keeps the typed values and * shows the message inside the row; success resets, closes and refreshes. */ export const ContactCreateRow = ({ formAction }: ContactCreateRowProps) => { const router = useRouter() const { open, setOpen } = useContactCreate() const formRef = useRef(null) const [hasName, setHasName] = useState(false) const [phone, setPhone] = useState('') const [formActionState, submitAction, isPending] = useActionState< CampaignFormActionState, FormData >(formAction, {}) const errorMessage = formActionState.status === 'success' ? undefined : firstFormActionMessage(formActionState) useEffect(() => { if (formActionState.status === 'success') { toast.success(formActionState.message) formRef.current?.reset() setHasName(false) setPhone('') setOpen(false) router.refresh() } }, [formActionState, router, setOpen]) if (!open) return null // C139 — manual dispatch (no `action={submitAction}`): React 19 resets // uncontrolled fields after any settled form action, wiping the typed name // on a validation/conflict error — the row stays open, so the wipe showed. // `startTransition` keeps `isPending` correct for the imperative dispatch. const handleSubmit = (event: FormEvent) => { event.preventDefault() startTransition(() => submitAction(new FormData(event.currentTarget))) } return (
setHasName(event.currentTarget.value.trim().length >= 2)} />
setPhone( formatBrazilianPhoneInput(sanitizeBrazilianPhoneInput(event.currentTarget.value)), ) } />
{errorMessage ? (

{errorMessage}

) : null}
) }