"use client"; import { ExtraFieldInput, isExtraFieldType } from "@/components/shared/FormFieldExtras"; import React, { Suspense, useEffect, useMemo, useState } from "react"; import { useSearchParams, useRouter } from "next/navigation"; import { useAuth } from "@/hooks/useAuth"; import { apiFetch, fetchEvent } from "@/lib/api"; import { Navbar } from "@/components/layout/Navbar"; import { Footer } from "@/components/layout/Footer"; import { FileText } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import type { Registration } from "@/types"; // Types for form fields type FormField = { id: string; type: 'yes_no'|'text'|'date'|'numeric'|'statement'|'paragraph'|'rating'|'multiple_choice'; label: string; isRequired?: boolean; helpText?: string|null; options?: unknown }; function FormsContent() { const search = useSearchParams(); const router = useRouter(); const { token } = useAuth(); const registrationId = search.get("registrationId"); // Donation chosen on the register form — passed through so the success page can add it to the payment. const donationParam = search.get("donation") ? `&donation=${encodeURIComponent(search.get("donation")!)}` : ""; // Set when a named attendee opens the link sent to them — show only their form. const onlyAttendeeId = search.get("attendeeId"); const [registration, setRegistration] = useState(null); const [eventForm, setEventForm] = useState<{ isRequired: boolean; fields: FormField[] } | null>(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [info, setInfo] = useState(null); // Local entry state for new responses, keyed by form block (see `blocks` below) const [formsData, setFormsData] = useState>>({}); useEffect(() => { (async () => { if (!registrationId) return; setLoading(true); setError(null); setInfo(null); try { // authToken optional — guests access via registrationId alone const reg = await apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}`, { authToken: token || undefined }); setRegistration(reg); const ev = await fetchEvent<{ form?: { isRequired: boolean; fields: FormField[] } | null }>(reg.eventId); if (ev?.form) setEventForm(ev.form); // Load any saved draft to prefill fields try { const draft = await apiFetch<{ data?: Record> } | null>(`/api/registrations/${encodeURIComponent(registrationId)}/forms/draft`, { authToken: token || undefined }); if (draft && draft.data && typeof draft.data === 'object') setFormsData(draft.data); } catch {} } catch (e) { setError(errorMessage(e) || 'Failed to load registration'); } finally { setLoading(false); } })(); }, [token, registrationId]); const submittedCount = useMemo(() => { return (registration?.formResponses || []).length; }, [registration]); const requiredCount = useMemo(() => { if (!registration) return 0; try { return (registration.registrationOptions || []) .filter((ro) => ro.eventOption?.isMainTicket) .reduce((s, ro) => s + (ro.quantity || 0), 0); } catch { return 0; } }, [registration]); // One form block per place still to fill: each named attendee (group tickets) by name, // then numbered blocks for unnamed places. Unnamed blocks keep their old numeric keys, // so drafts saved before attendees existed still prefill. type FormBlock = { key: string; label: string; attendeeId?: string }; const blocks = useMemo((): FormBlock[] => { if (!registration) return []; const responses = registration.formResponses || []; const answered = new Set(responses.map((r) => r.attendeeId).filter(Boolean)); const attendees = registration.attendees || []; const named = attendees .filter(a => !answered.has(a.id)) .map(a => ({ key: `a:${a.id}`, label: a.name, attendeeId: a.id })); const unnamedPlaces = Math.max(0, requiredCount - attendees.length); const unnamedAnswered = responses.filter((r) => !r.attendeeId).length; const unnamed = Array.from({ length: Math.max(0, unnamedPlaces - unnamedAnswered) }, (_, i) => ({ key: String(i), label: `Attendee ${unnamedAnswered + i + 1}`, })); const all: FormBlock[] = [...named, ...unnamed]; return onlyAttendeeId ? all.filter(b => b.attendeeId === onlyAttendeeId) : all; }, [registration, requiredCount, onlyAttendeeId]); const remaining = blocks.length; const attendeeName = (id: string | null | undefined) => (registration?.attendees || []).find((a) => a.id === id)?.name; // Determine if all required fields are filled for each attendee form to be submitted const canSubmit = useMemo(() => { if (!eventForm || remaining <= 0) return false; const reqFields = (eventForm.fields || []) .filter(f => !!f.isRequired && f.type !== 'statement' && f.type !== 'paragraph') .map(f => f.id); for (const b of blocks) { const data = formsData[b.key] || {}; for (const fid of reqFields) { const v = data[fid]; if (v === undefined || v === null || String(v).trim() === '') { return false; } } } return true; }, [eventForm, formsData, remaining, blocks]); const submit = async () => { if (!registrationId) return; try { setError(null); setInfo(null); const payload = blocks.map(b => ({ ...(b.attendeeId ? { attendeeId: b.attendeeId } : {}), answers: formsData[b.key] || {} })); if (payload.length === 0) { // Nothing left to submit – still go to success page to continue the flow const totalDue = (registration?.registrationOptions || []).reduce((s, ro) => s + ((ro.eventOption?.price || 0) * (ro.quantity || 0)), 0); router.push(`/registration/success?registrationId=${encodeURIComponent(registrationId)}${totalDue>0?`&totalDue=${encodeURIComponent(totalDue.toFixed(2))}`:''}${donationParam}`); return; } await apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}/forms/responses`, { method: 'POST', authToken: token || undefined, body: { responses: payload } }); // On success, redirect to the success page const totalDue = (registration?.registrationOptions || []).reduce((s, ro) => s + ((ro.eventOption?.price || 0) * (ro.quantity || 0)), 0); router.push(`/registration/success?registrationId=${encodeURIComponent(registrationId)}${totalDue>0?`&totalDue=${encodeURIComponent(totalDue.toFixed(2))}`:''}${donationParam}`); } catch (e) { setError(errorMessage(e) || 'Failed to submit forms'); } }; const saveDraft = async () => { if (!registrationId) return; try { setError(null); setInfo(null); await apiFetch(`/api/registrations/${encodeURIComponent(registrationId)}/forms/draft`, { method: 'PUT', authToken: token || undefined, body: { data: formsData } }); setInfo('Draft saved. You can come back and finish later.'); if (!token || !registrationId) return; try { // Redirect to the success page const totalDue = (registration?.registrationOptions || []).reduce((s, ro) => s + ((ro.eventOption?.price || 0) * (ro.quantity || 0)), 0); router.push(`/registration/success?registrationId=${encodeURIComponent(registrationId)}${totalDue>0?`&totalDue=${encodeURIComponent(totalDue.toFixed(2))}`:''}${donationParam}`); } catch (e) { setError(errorMessage(e) || 'Failded to go to next step'); } } catch (e) { setError(errorMessage(e) || 'Failed to save draft'); } }; const skip = async () => { if (!registrationId) return; try { // Redirect to the success page const totalDue = (registration?.registrationOptions || []).reduce((s, ro) => s + ((ro.eventOption?.price || 0) * (ro.quantity || 0)), 0); router.push(`/registration/success?registrationId=${encodeURIComponent(registrationId)}${totalDue>0?`&totalDue=${encodeURIComponent(totalDue.toFixed(2))}`:''}${donationParam}`); } catch (e) { setError(errorMessage(e) || 'Failded to skip'); } }; if (!registrationId) { return (
Missing registrationId.
); } return (

Attendee forms

{loading &&
Loading…
} {error &&
{error}
} {info &&
{info}
} {registration && (
{registration.event?.title || registration.eventId}
Registration #{registration.id.slice(0,8)}
Forms submitted: {submittedCount} / {requiredCount}
)} {/* Existing responses (read-only list) */} {registration && (registration.formResponses || []).length > 0 && (
Submitted responses
    {(registration.formResponses || []).map((resp, idx) => (
  • {attendeeName(resp.attendeeId) || `Attendee ${idx + 1}`}
    {(resp.answers || []).length === 0 ? (
    No answers recorded.
    ) : (
      {(resp.answers || []).map((a) => (
    • {eventForm?.fields.find(f => f.id === a.fieldId)?.label || (`Field ${a.fieldId}`)}: {a.value}
    • ))}
    )}
  • ))}
)} {/* Remaining forms to fill */} {eventForm && remaining > 0 && (
Fill remaining attendee details ({remaining})
{blocks.map(({ key: idx, label }) => (
{label}
{eventForm.fields.map((f) => (
{f.type === 'statement' ? (
{f.label}
) : f.type === 'paragraph' ? (
{f.label &&
{f.label}
} {f.helpText &&
{f.helpText}
}
) : ( <> {isExtraFieldType(f.type) ? ( setFormsData(prev => ({ ...prev, [idx]: { ...(prev[idx]||{}), [f.id]: v } }))} /> ) : f.type === 'yes_no' ? ( ) : f.type === 'date' ? ( setFormsData(prev => ({ ...prev, [idx]: { ...(prev[idx]||{}), [f.id]: e.target.value } }))} /> ) : f.type === 'numeric' ? ( setFormsData(prev => ({ ...prev, [idx]: { ...(prev[idx]||{}), [f.id]: e.target.value } }))} /> ) : ( setFormsData(prev => ({ ...prev, [idx]: { ...(prev[idx]||{}), [f.id]: e.target.value } }))} /> )} {f.helpText &&
{f.helpText}
} )}
))}
))}
{!onlyAttendeeId && ( )}
)} {eventForm && remaining === 0 && (
All required attendee forms are completed for this registration.
)}
); } export default function FormsPage() { return ( Loading…}> ); }