'use client' import { useId, useState } from 'react' import { PlusIcon, Trash2Icon } from 'lucide-react' import { ContactCombobox, type ContactComboboxOption } from '@/components/campaign/ContactCombobox' import { Button } from '@/components/ui/button' import { Field, FieldError, FieldLabel } from '@/components/ui/field' import { Input } from '@/components/ui/input' import { formatIsoAsBahiaDateTimeInput } from '@/utilities/campaignTime' export type ActionPlanTaskFieldValue = { key: string title: string responsible: ContactComboboxOption | null due: string done: boolean } type ActionPlanTaskFieldsProps = { initialTasks: Array<{ id: string | null title: string responsible: ContactComboboxOption | null due: string | null done: boolean }> searchContacts: (query: string) => Promise error?: string } let taskKeySequence = 0 const nextTaskKey = (): string => { taskKeySequence += 1 return `new-${taskKeySequence}` } const serializeTasks = (tasks: ActionPlanTaskFieldValue[]) => JSON.stringify( tasks .filter((task) => task.title.trim().length > 0) .map((task) => ({ title: task.title.trim(), ...(task.responsible ? { responsible: task.responsible.id } : {}), ...(task.due ? { due: task.due } : {}), done: task.done, })), ) export const ActionPlanTaskFields = ({ initialTasks, searchContacts, error, }: ActionPlanTaskFieldsProps) => { const fieldId = useId() const [tasks, setTasks] = useState(() => initialTasks.map((task) => ({ key: task.id ?? nextTaskKey(), title: task.title, responsible: task.responsible, due: task.due ? formatIsoAsBahiaDateTimeInput(task.due) : '', done: task.done, })), ) const updateTask = (key: string, patch: Partial) => { setTasks((current) => current.map((task) => (task.key === key ? { ...task, ...patch } : task))) } const addTask = () => { setTasks((current) => [ ...current, { key: nextTaskKey(), title: '', responsible: null, due: '', done: false }, ]) } const removeTask = (key: string) => { setTasks((current) => current.filter((task) => task.key !== key)) } return ( Tarefas
{tasks.map((task, index) => (
updateTask(task.key, { title: event.target.value })} /> updateTask(task.key, { responsible: contact })} /> updateTask(task.key, { due: event.target.value })} />
))}
{error ? {error} : null}
) }