"use client"; import { useEffect, useState, type FormEvent } from "react"; import { Button } from "@/app/components/ui/button"; import { Checkbox } from "@/app/components/ui/checkbox"; import { Input } from "@/app/components/ui/input"; import { Label } from "@/app/components/ui/label"; import { Switch } from "@/app/components/ui/switch"; import { DatePicker } from "@/app/components/ui/date-picker"; import { ErrorState } from "@/app/components/ui/states"; import { listSalespersonOptions } from "@/app/lib/services/adminEvents"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import type { AdminEvent, AdminEventPayload, SalespersonOption } from "@/app/lib/types"; import type { ApiError } from "@/app/lib/clientApi"; interface SalespersonOptionExtended extends SalespersonOption { active: boolean; } export interface EventFormProps { initial?: AdminEvent; onSubmit: (payload: AdminEventPayload) => Promise; submitLabel?: string; } /** Missing-field codes the API lists in errors[], mapped to the message shown under that field. */ const REQUIRED_MESSAGE: Record = { name: "EvtNameRequired", location: "EvtLocationRequired", startDate: "EvtStartRequired", endDate: "EvtEndRequired", }; /** Fields the form can show an API error under; anything else goes to the top of the form. */ const FIELD_ERROR_SLOTS = ["name", "location", "startDate", "endDate", "salespersonIds"]; export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) { const t = useT(); const [name, setName] = useState(initial?.name ?? ""); const [location, setLocation] = useState(initial?.location ?? ""); const [startDate, setStartDate] = useState(initial?.startDate ?? ""); const [endDate, setEndDate] = useState(initial?.endDate ?? ""); const [enabled, setEnabled] = useState(initial?.enabled ?? true); const [optionList, setOptionList] = useState([]); const [loadingPickers, setLoadingPickers] = useState(true); const [pickersError, setPickersError] = useState(null); const [fieldErrors, setFieldErrors] = useState>({}); const [formError, setFormError] = useState(null); const [saving, setSaving] = useState(false); useEffect(() => { let cancelled = false; // eslint-disable-next-line react-hooks/set-state-in-effect -- loading/picker reset is the actual synchronization; initial is in the deps below. setLoadingPickers(true); setPickersError(null); listSalespersonOptions() .then((opts) => { if (cancelled) return; const activeOpts = opts.map((o) => ({ ...o, active: true } as SalespersonOptionExtended)); // Merge deactivated team members from initial. const activeIds = new Set(activeOpts.map((o) => o.id)); if (initial?.team) { for (const m of initial.team) { if (m.id != null && !activeIds.has(m.id)) { activeOpts.push({ id: m.id as number, name: m.name ?? "", username: m.username ?? "", active: false, }); } } } setOptionList(activeOpts); }) .catch((err: unknown) => { if (!cancelled) { setPickersError(err instanceof Error ? err.message : "SetupLoadOptionsFailed"); } }) .finally(() => { if (!cancelled) setLoadingPickers(false); }); return () => { cancelled = true; }; }, [initial]); // Build the set of initially selected team member IDs. // Members from initial.team that are also in the active options → checked. // Members from initial.team that are NOT in the options (deactivated) → still shown, checked, with "Inactive" marker. const [selectedIds, setSelectedIds] = useState>(() => { if (!initial?.team) return new Set(); return new Set(initial.team.map((m) => m.id).filter((id): id is number => id != null)); }); function toggleSalesperson(id: number) { setSelectedIds((prev) => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; }); } async function handleSubmit(event: FormEvent) { event.preventDefault(); const trimmedName = name.trim(); const trimmedLocation = location.trim(); const errors: Record = {}; if (!trimmedName) errors.name = t("EvtNameRequired"); if (!trimmedLocation) errors.location = t("EvtLocationRequired"); if (!startDate) errors.startDate = t("EvtStartRequired"); if (!endDate) errors.endDate = t("EvtEndRequired"); if (endDate && startDate && endDate < startDate) errors.endDate = t("EvtEndBeforeStart"); if (trimmedName.length > 100) errors.name = t("EvtNameTooLong"); if (trimmedLocation.length > 200) errors.location = t("EvtLocationTooLong"); setFieldErrors(errors); if (Object.keys(errors).length > 0) return; setFormError(null); setSaving(true); try { const payload: AdminEventPayload = { name: trimmedName, location: trimmedLocation, startDate, endDate, salespersonIds: Array.from(selectedIds).filter((id): id is number => id != null), }; // `enabled` is only sent on edit (when initial exists). if (initial) { payload.enabled = enabled; } await onSubmit(payload); } catch (err) { if (err instanceof Error && "status" in err && "data" in err) { // The API sends errors[] (every missing field) and details.field (the failing field). const data = (err as ApiError).data as { errors?: unknown; details?: { field?: unknown } } | undefined; const missing = (Array.isArray(data?.errors) ? data.errors : []).filter((f): f is string => typeof f === "string" && Object.hasOwn(REQUIRED_MESSAGE, f)); const field = data?.details?.field; if (missing.length > 0) { setFieldErrors(Object.fromEntries(missing.map((f) => [f, t(REQUIRED_MESSAGE[f])]))); return; } if (typeof field === "string" && FIELD_ERROR_SLOTS.includes(field)) { setFieldErrors({ [field]: err.message }); return; } } setFormError(err instanceof Error ? err.message : "EvtSaveFailed"); } finally { setSaving(false); } } const label = submitLabel ?? (initial ? t("Edit") : t("Create")); return (
{formError && } {pickersError && }
setName(e.target.value)} disabled={saving} aria-invalid={!!fieldErrors.name} /> {fieldErrors.name && (

{fieldErrors.name}

)}
setLocation(e.target.value)} disabled={saving} aria-invalid={!!fieldErrors.location} /> {fieldErrors.location && (

{fieldErrors.location}

)}
{fieldErrors.startDate && (

{fieldErrors.startDate}

)}
{fieldErrors.endDate && (

{fieldErrors.endDate}

)}
{initial && (
)}
{t("EvtTeamLabel")} {fieldErrors.salespersonIds && (

{fieldErrors.salespersonIds}

)}
{loadingPickers ? (

{t("Loading")}

) : ( optionList.map((opt) => { const name = opt.name ?? ""; const username = opt.username ?? ""; const displayName = name || username || String(opt.id); const displayUsername = name ? username : undefined; return (
toggleSalesperson(opt.id)} aria-label={displayUsername ? `${displayName} (${displayUsername})` : displayName} />
); }) )}
); }