import { useState } from "react"; import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragOverlay, } from "@dnd-kit/core"; import type { DragEndEvent, DragStartEvent } from "@dnd-kit/core"; import { arrayMove, SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy, useSortable, } from "@dnd-kit/sortable"; import { CSS } from "@dnd-kit/utilities"; import { Trash2, Plus, ArrowRight, GripVertical, ChevronDown, ChevronsDownUp, ChevronsUpDown, } from "lucide-react"; import { Button } from "../../../../components/ui/button"; import { Card } from "../../../../components/ui/card"; import { Input } from "../../../../components/ui/input"; import { DynamicSchemaSlotField } from "../../../../components/content-management/DynamicSchemaSlotField"; import type { QuestionTypeDefinition } from "../../../../types/questionTypeDefinition.types"; import { questionTypeDefinitionListLabel } from "../../../../api/questionTypeDefinitions.api"; import { definitionUsesDynamicPayload, emptyDynamicFieldValuesForDefinition, legacyQuestionTypeFromDefinition, } from "../../../../lib/learnEnglishDefinitionQuestion"; import { validateLearnEnglishQuestionsWithDefinitions } from "../../../../lib/learnEnglishPracticePublish"; import { cn } from "../../../../lib/utils"; import { toast } from "sonner"; function syncQuestionDisplayOrders( questions: T[], ): T[] { return questions.map((q, index) => ({ ...q, displayOrder: index + 1 })); } function truncateText(value: string, max = 100): string { const trimmed = value.trim(); return trimmed.length > max ? `${trimmed.slice(0, max)}…` : trimmed; } function questionSummaryPreview( q: { text?: string; dynamicFieldValues?: Record; questionTypeDefinitionId?: number | null; difficultyLevel?: string; points?: number; }, def: QuestionTypeDefinition | undefined, ): string { const text = String(q.text ?? "").trim(); if (text) return truncateText(text); const values = Object.values(q.dynamicFieldValues ?? {}) .map((v) => String(v ?? "").trim()) .filter((v) => v && !v.startsWith("{") && !v.startsWith("[")); if (values[0]) return truncateText(values[0]); if (def) return questionTypeDefinitionListLabel(def); return "No content yet"; } function QuestionCollapsibleBody({ expanded, children, }: { expanded: boolean; children: React.ReactNode; }) { return (
{children}
); } interface SortableQuestionCardProps { id: string; children: (opts: { dragHandleProps: React.HTMLAttributes; isDragging: boolean; }) => React.ReactNode; } function SortableQuestionCard({ id, children }: SortableQuestionCardProps) { const { attributes, listeners, setNodeRef, transform, transition, isDragging, } = useSortable({ id }); const style = { transform: CSS.Transform.toString(transform), transition, }; return (
{children({ isDragging, dragHandleProps: { ...attributes, ...listeners, type: "button", }, })}
); } function defaultMcqOptions() { return [ { text: "", isCorrect: true }, { text: "", isCorrect: false }, { text: "", isCorrect: false }, { text: "", isCorrect: false }, ]; } function createEmptyQuestionRow(id: string, displayOrder = 1) { return { id, displayOrder, serverQuestionId: null as number | null, questionTypeDefinitionId: null as number | null, text: "", difficultyLevel: "EASY" as "EASY" | "MEDIUM" | "HARD", points: 1, dynamicFieldValues: {} as Record, mcqOptions: defaultMcqOptions(), trueFalseCorrect: true, shortAnswers: [""], }; } interface QuestionsStepProps { formData: any; setFormData: (data: any) => void; nextStep: () => void; prevStep: () => void; typeDefinitions: QuestionTypeDefinition[]; definitionsLoading: boolean; definitionsError: string | null; } export function QuestionsStep({ formData, setFormData, nextStep, prevStep, typeDefinitions, definitionsLoading, definitionsError, }: QuestionsStepProps) { const [activeDragId, setActiveDragId] = useState(null); const [expandedQuestionIds, setExpandedQuestionIds] = useState>( () => new Set(formData.questions[0]?.id ? [formData.questions[0].id] : []), ); const sensors = useSensors( useSensor(PointerSensor, { activationConstraint: { distance: 8 } }), useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates, }), ); const questionIds = formData.questions.map((q: { id: string }) => q.id); const canReorder = formData.questions.length > 1; const activeDragIndex = activeDragId ? formData.questions.findIndex((q: { id: string }) => q.id === activeDragId) : -1; const reorderQuestions = (activeId: string, overId: string) => { const oldIndex = formData.questions.findIndex( (q: { id: string }) => q.id === activeId, ); const newIndex = formData.questions.findIndex( (q: { id: string }) => q.id === overId, ); if (oldIndex === -1 || newIndex === -1) return; setFormData({ ...formData, questions: syncQuestionDisplayOrders( arrayMove(formData.questions, oldIndex, newIndex), ), }); }; const toggleQuestionExpanded = (id: string) => { setExpandedQuestionIds((prev) => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; }); }; const collapseAllQuestions = () => setExpandedQuestionIds(new Set()); const expandAllQuestions = () => setExpandedQuestionIds(new Set(questionIds)); const handleDragStart = (event: DragStartEvent) => { setActiveDragId(String(event.active.id)); collapseAllQuestions(); }; const handleDragEnd = (event: DragEndEvent) => { const { active, over } = event; if (over && active.id !== over.id) { reorderQuestions(String(active.id), String(over.id)); } setActiveDragId(null); }; const applyDefinitionToQuestion = ( index: number, definitionId: number, defs: QuestionTypeDefinition[], ) => { const def = defs.find((d) => d.id === definitionId); const newQuestions = [...formData.questions]; const row = { ...newQuestions[index], questionTypeDefinitionId: definitionId }; if (def) { row.dynamicFieldValues = emptyDynamicFieldValuesForDefinition(def); } newQuestions[index] = row; setFormData({ ...formData, questions: newQuestions }); }; const setDynamicValue = (qIndex: number, key: string, value: string) => { const newQuestions = [...formData.questions]; newQuestions[qIndex] = { ...newQuestions[qIndex], dynamicFieldValues: { ...(newQuestions[qIndex].dynamicFieldValues ?? {}), [key]: value, }, }; setFormData({ ...formData, questions: newQuestions }); }; const addQuestion = () => { const id = `q${Date.now()}`; const row = createEmptyQuestionRow(id); if (typeDefinitions[0]) { row.questionTypeDefinitionId = typeDefinitions[0].id; row.dynamicFieldValues = emptyDynamicFieldValuesForDefinition( typeDefinitions[0], ); } setFormData({ ...formData, questions: syncQuestionDisplayOrders([...formData.questions, row]), }); setExpandedQuestionIds(new Set([id])); }; const renderTypeSpecificFields = (q: any, i: number, def: QuestionTypeDefinition) => { if (definitionUsesDynamicPayload(def)) { return (

Image, audio, and PDF use upload or URL.{" "} Table uses the visual table builder. Timer and prep-time slots use seconds. Other slots use text or structured JSON where noted.

{def.stimulus_schema.length > 0 ? (

Stimulus

{def.stimulus_schema.map((row) => (
setDynamicValue(i, `stimulus:${row.id}`, next) } allFieldValues={q.dynamicFieldValues} stimulusSchema={def.stimulus_schema} responseSchema={def.response_schema} />
))}
) : null} {def.response_schema.length > 0 ? (

Response

{def.response_schema.map((row) => (
setDynamicValue(i, `response:${row.id}`, next) } allFieldValues={q.dynamicFieldValues} stimulusSchema={def.stimulus_schema} responseSchema={def.response_schema} />
))}
) : null}
); } const legacy = legacyQuestionTypeFromDefinition(def); if (legacy === "MCQ") { return (
{(q.mcqOptions ?? defaultMcqOptions()).map( (opt: { text: string; isCorrect: boolean }, j: number) => (
{ const newQuestions = [...formData.questions]; const opts = [ ...(newQuestions[i].mcqOptions ?? defaultMcqOptions()), ]; opts[j] = { ...opts[j], text: e.target.value }; newQuestions[i].mcqOptions = opts; setFormData({ ...formData, questions: newQuestions }); }} className="min-w-0 flex-1 rounded-lg border-grayScale-200" placeholder={`Option ${j + 1}`} />
), )}
); } if (legacy === "TRUE_FALSE") { return (
Correct answer
); } if (legacy === "SHORT_ANSWER") { return (
{(q.shortAnswers ?? [""]).map((line: string, j: number) => (
{ const newQuestions = [...formData.questions]; const lines = [...(newQuestions[i].shortAnswers ?? [""])]; lines[j] = e.target.value; newQuestions[i].shortAnswers = lines; setFormData({ ...formData, questions: newQuestions }); }} className="rounded-lg border-grayScale-200" placeholder="Acceptable wording" />
))}
); } return (

This definition has no schema rows and is not mapped to MCQ / True‑False / Short answer. It will be submitted as{" "} DYNAMIC with an empty payload.

); }; return (

Questions

Choose a question type for each item, then fill in the fields that type requires. Collapse cards to compare and drag them into order. Questions are saved when you publish or save the practice.

{formData.questions.length > 1 ? (
) : null} {definitionsError ? (
{definitionsError}
) : null} {definitionsLoading ? (

Loading question types…

) : null}
{formData.questions.map((q: any, i: number) => { const def = typeDefinitions.find( (d) => d.id === q.questionTypeDefinitionId, ); const isExpanded = expandedQuestionIds.has(q.id); const summary = questionSummaryPreview(q, def); const typeLabel = def ? questionTypeDefinitionListLabel(def) : "No type selected"; return ( {({ dragHandleProps, isDragging }) => (
{canReorder ? ( ) : null}
{ const newQuestions = [...formData.questions]; const parsed = Number.parseInt(e.target.value, 10); newQuestions[i] = { ...newQuestions[i], points: Number.isFinite(parsed) && parsed > 0 ? parsed : 1, }; setFormData({ ...formData, questions: newQuestions }); }} className="h-11 rounded-lg border-grayScale-200" />
{def?.description ? (

{def.description}

) : null}
{def && !definitionUsesDynamicPayload(def) ? (
{ const newQuestions = [...formData.questions]; newQuestions[i].text = e.target.value; setFormData({ ...formData, questions: newQuestions }); }} className="min-h-[52px] rounded-xl border-grayScale-200 px-4 py-3 text-base font-medium text-grayScale-700" placeholder="Question prompt for learners" />
) : def && definitionUsesDynamicPayload(def) ? (

Enter the question prompt in the text or instruction field below, along with any other required content for this type.

) : null} {def ? renderTypeSpecificFields(q, i, def) : null}
)} ); })}
{activeDragId && activeDragIndex >= 0 ? (
{(() => { const dragged = formData.questions[activeDragIndex]; const draggedDef = typeDefinitions.find( (d) => d.id === dragged?.questionTypeDefinitionId, ); return (

Question{" "} {dragged?.displayOrder ?? activeDragIndex + 1}

{draggedDef ? questionTypeDefinitionListLabel(draggedDef) : "No type selected"}

{questionSummaryPreview(dragged, draggedDef)}

); })()} ) : null}
); }