"use client";
import { useEffect, useState, type ReactNode } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { ArrowDown, ArrowUp, Plus, Trash2 } from "lucide-react";
import { Button } from "@/app/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/app/components/ui/radio-group";
import { Textarea } from "@/app/components/ui/textarea";
import { ErrorState } from "@/app/components/ui/states";
import { FieldError } from "@/app/components/catalog-setup/FieldError";
import { parseServerError, type FieldErrors } from "@/app/lib/catalogSetup";
import {
draftFromView,
emptyForm,
FIELD_LABELS,
FIELD_TYPES,
formBody,
moveField,
newField,
type CmsFormDraft,
type CmsFormFieldDraft,
type FieldType,
} from "@/app/lib/cmsForms";
import { deleteForm, getForm, saveForm } from "@/app/lib/services/adminForms";
import { ApiError } from "@/app/lib/clientApi";
import { useT } from "@/app/lib/i18n/MessagesProvider";
// The form editor (add-cms-forms): settings plus an ordered field list. Each field keeps the key it
// was created with, so stored submissions stay matched to it after relabelling or reordering.
const SELECT_CLASS =
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm disabled:cursor-not-allowed disabled:opacity-50";
function Field({ id, label, error, name, children }: { id: string; label: string; error?: string; name?: string; children: ReactNode }) {
return (
{children}
);
}
/** Server error paths this editor shows under a field; any other path goes to the summary alert. */
const RENDERED = /^(name|submitLabel|successMessage|status|fields|notifyEmails(\[\d+\])?|fields\[\d+\]\.(key|label|type|options))$/;
/** The first message among errors whose path is `name` or `name[i]` (e.g. notifyEmails[1]). */
function firstError(errors: FieldErrors, name: string): string | undefined {
const hit = Object.entries(errors).find(([path]) => path === name || path.startsWith(`${name}[`));
return hit?.[1];
}
export function FormEditor({ formId }: { formId?: number }) {
const t = useT();
const router = useRouter();
const justSaved = useSearchParams()?.get("saved") === "1";
const [draft, setDraft] = useState(() => emptyForm());
const [loading, setLoading] = useState(formId != null);
const [loadError, setLoadError] = useState(null);
const [errors, setErrors] = useState({});
const [summary, setSummary] = useState(null);
const [notice, setNotice] = useState(justSaved ? "FrmSaved" : null);
const [saving, setSaving] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
useEffect(() => {
if (formId == null) return;
let cancelled = false;
getForm(formId)
.then((view) => {
if (!cancelled) setDraft(draftFromView(view));
})
.catch((err: unknown) => {
if (!cancelled) setLoadError(err instanceof Error ? err.message : "FrmLoadFailed");
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [formId]);
const patch = (next: Partial) => setDraft((d) => ({ ...d, ...next }));
// Field errors are keyed by position, so any reorder or removal clears them.
const setFields = (fields: CmsFormFieldDraft[]) => {
setErrors({});
patch({ fields });
};
const updateField = (key: string, next: Partial) =>
setDraft((d) => ({ ...d, fields: d.fields.map((f) => (f.key === key ? { ...f, ...next } : f)) }));
async function save() {
setSummary(null);
setNotice(null);
setErrors({});
setSaving(true);
try {
const view = await saveForm(formBody(draft));
setDraft((d) => ({ ...d, id: view.id }));
setNotice("FrmSaved");
if (draft.id == null) router.replace(`/forms/${view.id}?saved=1`);
} catch (err) {
const message = err instanceof Error ? err.message : "FrmSaveFailed";
const { path, message: fieldMessage } = parseServerError(message);
if (err instanceof ApiError && err.status === 422 && path && RENDERED.test(path)) setErrors({ [path]: fieldMessage });
else setSummary(message);
} finally {
setSaving(false);
}
}
async function remove() {
if (draft.id == null) return;
try {
await deleteForm(draft.id);
router.push("/forms");
} catch (err) {
setSummary(err instanceof Error ? err.message : "FrmDeleteFailed");
}
}
if (loadError) return ;
if (loading) return null;
const fieldError = (index: number, name: string) => errors[`fields[${index}].${name}`];
return (