import { Button } from "@repo/shadcn-ui/components/button"; import { ArrowDownIcon, ArrowUpIcon, Trash2Icon } from "lucide-react"; import { useId } from "react"; import type { FieldSection } from "./field-sections"; import { SelectWithAction } from "./select-with-action"; import { SwitchField } from "./switch-field"; import type { SectionBinding, SectionEditorLabels } from "./template-sections-editor"; export function TemplateSectionFields({ sectionId, sections, fields, fieldNames, fieldNotes, labels, disabled, onChange, }: { sectionId?: string | undefined; sections: readonly FieldSection[]; fields: readonly SectionBinding[]; fieldNames: Readonly>; fieldNotes?: Readonly> | undefined; labels: SectionEditorLabels; disabled: boolean; onChange: (fields: SectionBinding[]) => void; }) { const prefix = useId(); const grouped = fields.filter((field) => field.sectionId === sectionId); const move = (fieldId: string, offset: number) => { const position = grouped.findIndex((field) => field.fieldId === fieldId); const neighbor = grouped[position + offset]; const current = grouped[position]; if (!(neighbor && current)) { return; } const next = [...fields]; const index = fields.indexOf(current); const other = fields.indexOf(neighbor); next[index] = neighbor; next[other] = current; onChange(next); }; if (!(sectionId || grouped.length)) { return null; } return (
{!sectionId && sections.length > 0 && (

{labels.ungrouped}

)} {!grouped.length &&

{labels.empty}

} {grouped.map((field, index) => { const name = fieldNames[field.fieldId] ?? field.fieldId; return (

{name}

{fieldNotes?.[field.fieldId] && (

{fieldNotes[field.fieldId]}

)}
{labels.required} : {name} } onCheckedChange={(required) => onChange( fields.map((item) => item.fieldId === field.fieldId ? { ...item, required } : item ) ) } /> {sections.length > 0 && (
onChange( fields.map((item) => item.fieldId === field.fieldId ? { fieldId: item.fieldId, required: item.required, ...(section ? { sectionId: section } : {}), } : item ) ) } options={[ ...sections.map((section) => ({ value: section.id, label: section.name || labels.name, })), ]} placeholder={labels.ungrouped} value={field.sectionId ?? ""} />
)}
); })}
); }