import { useCallback, useEffect, useMemo, useState } from "react" import { CheckCircle2, ClipboardList, HelpCircle, Pencil, Plus, RefreshCw, Save, Search, Trash2, X, } from "lucide-react" import { toast } from "sonner" import { createAndAttachPlacementQuestion, detachPlacementQuestion, ensurePlacementAssessmentSet, getPlacementQuestionDetail, listPlacementQuestions, savePlacementAssessmentSet, type PlacementQuestionDetail, type PlacementQuestionRow, } from "../../api/initial-assessment.api" import { updateQuestion } from "../../api/courses.api" import { notifyApiError } from "../../lib/apiErrors" import { DEFAULT_TABLE_PAGE_SIZE } from "../../lib/tablePagination" import { InitialAssessmentThresholdsTab } from "../settings/InitialAssessmentThresholdsTab" import { TablePagination } from "../../components/admin/TablePagination" import { Badge } from "../../components/ui/badge" import { Button } from "../../components/ui/button" import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card" import { Input } from "../../components/ui/input" import { Select } from "../../components/ui/select" import { SpinnerIcon } from "../../components/ui/spinner-icon" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../components/ui/table" import { Textarea } from "../../components/ui/textarea" import { ToggleSwitch } from "../../components/ui/toggle-switch" import { cn } from "../../lib/utils" import type { QuestionSetDetail } from "../../types/course.types" type TabId = "set" | "questions" | "thresholds" type DraftQuestionType = "MCQ" | "TRUE_FALSE" interface DraftOption { text: string isCorrect: boolean } interface QuestionDraft { questionText: string questionType: DraftQuestionType difficulty: "EASY" | "MEDIUM" | "HARD" points: number options: DraftOption[] tips: string explanation: string } const emptyDraft = (): QuestionDraft => ({ questionText: "", questionType: "MCQ", difficulty: "EASY", points: 1, options: [ { text: "", isCorrect: true }, { text: "", isCorrect: false }, { text: "", isCorrect: false }, { text: "", isCorrect: false }, ], tips: "", explanation: "", }) const typeColors: Record = { MCQ: "bg-blue-50 text-blue-700 ring-1 ring-inset ring-blue-200", TRUE_FALSE: "bg-brand-100 text-brand-700 ring-1 ring-inset ring-brand-200", SHORT_ANSWER: "bg-mint-100 text-green-700 ring-1 ring-inset ring-green-200", SHORT: "bg-mint-100 text-green-700 ring-1 ring-inset ring-green-200", AUDIO: "bg-purple-100 text-purple-700 ring-1 ring-inset ring-purple-200", DYNAMIC: "bg-amber-50 text-amber-800 ring-1 ring-inset ring-amber-200", } const typeLabels: Record = { MCQ: "Multiple choice", TRUE_FALSE: "True / False", SHORT_ANSWER: "Short answer", SHORT: "Short answer", AUDIO: "Audio", DYNAMIC: "Dynamic", } const difficultyColors: Record = { EASY: "bg-mint-50 text-green-700 ring-1 ring-inset ring-green-200", MEDIUM: "bg-amber-50 text-amber-800 ring-1 ring-inset ring-amber-200", HARD: "bg-red-50 text-red-700 ring-1 ring-inset ring-red-200", } function draftFromQuestionDetail(q: PlacementQuestionDetail): QuestionDraft { const rawType = String(q.question_type ?? "MCQ").toUpperCase() const questionType: DraftQuestionType = rawType === "TRUE_FALSE" ? "TRUE_FALSE" : "MCQ" const difficulty = q.difficulty_level === "MEDIUM" || q.difficulty_level === "HARD" ? q.difficulty_level : q.difficulty_level === "EASY" ? "EASY" : "EASY" const sortedOptions = [...(q.options ?? [])].sort( (a, b) => Number(a.option_order ?? 0) - Number(b.option_order ?? 0), ) let options: DraftOption[] if (questionType === "TRUE_FALSE") { const trueOpt = sortedOptions.find((o) => String(o.option_text).toLowerCase() === "true") const falseOpt = sortedOptions.find((o) => String(o.option_text).toLowerCase() === "false") const correctIsTrue = trueOpt?.is_correct ? true : falseOpt?.is_correct ? false : sortedOptions.find((o) => o.is_correct)?.option_text?.toLowerCase() !== "false" options = [ { text: "True", isCorrect: correctIsTrue }, { text: "False", isCorrect: !correctIsTrue }, ] } else { options = sortedOptions.map((o) => ({ text: String(o.option_text ?? ""), isCorrect: Boolean(o.is_correct), })) while (options.length < 2) { options.push({ text: "", isCorrect: false }) } if (!options.some((o) => o.isCorrect) && options.length > 0) { options[0] = { ...options[0], isCorrect: true } } } return { questionText: String(q.question_text ?? ""), questionType, difficulty, points: Number(q.points ?? 1) || 1, options, tips: String(q.tips ?? ""), explanation: String(q.explanation ?? ""), } } export function InitialAssessmentPage() { const [tab, setTab] = useState("set") const [loading, setLoading] = useState(true) const [savingSet, setSavingSet] = useState(false) const [setDetail, setSetDetail] = useState(null) const [title, setTitle] = useState("") const [description, setDescription] = useState("PLACEMENT") const [status, setStatus] = useState("DRAFT") const [shuffle, setShuffle] = useState(false) const [timeLimit, setTimeLimit] = useState("") const [questions, setQuestions] = useState([]) const [questionsLoading, setQuestionsLoading] = useState(false) const [addOpen, setAddOpen] = useState(false) const [editingQuestionId, setEditingQuestionId] = useState(null) const [editingStatus, setEditingStatus] = useState("PUBLISHED") const [formLoading, setFormLoading] = useState(false) const [draft, setDraft] = useState(emptyDraft) const [savingQuestion, setSavingQuestion] = useState(false) const [removingId, setRemovingId] = useState(null) const [statusUpdatingId, setStatusUpdatingId] = useState(null) const [questionsPage, setQuestionsPage] = useState(1) const [questionsPageSize, setQuestionsPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE) const [questionsSearch, setQuestionsSearch] = useState("") const loadSet = useCallback(async () => { setLoading(true) try { const detail = await ensurePlacementAssessmentSet() setSetDetail(detail) setTitle(detail.title || "Initial Placement Assessment") setDescription(detail.description || "PLACEMENT") setStatus(String(detail.status || "DRAFT").toUpperCase()) setShuffle(Boolean(detail.shuffle_questions)) setTimeLimit( detail.time_limit_minutes != null && detail.time_limit_minutes > 0 ? String(detail.time_limit_minutes) : "", ) } catch (e) { console.error(e) notifyApiError(e, "Failed to load placement assessment") setSetDetail(null) } finally { setLoading(false) } }, []) const loadQuestions = useCallback(async (setId: number) => { setQuestionsLoading(true) try { const rows = await listPlacementQuestions(setId) setQuestions(rows) } catch (e) { console.error(e) notifyApiError(e, "Failed to load placement questions") setQuestions([]) } finally { setQuestionsLoading(false) } }, []) useEffect(() => { void loadSet() }, [loadSet]) useEffect(() => { if (setDetail?.id && (tab === "questions" || tab === "set")) { void loadQuestions(setDetail.id) } }, [setDetail?.id, tab, loadQuestions]) const totalPoints = useMemo( () => questions.reduce((sum, q) => sum + (Number.isFinite(q.points) ? q.points : 0), 0), [questions], ) const questionsSorted = useMemo( () => [...questions].sort( (a, b) => a.displayOrder - b.displayOrder || a.questionId - b.questionId, ), [questions], ) const filteredQuestions = useMemo(() => { const q = questionsSearch.trim().toLowerCase() if (!q) return questionsSorted return questionsSorted.filter((row) => { const typeLabel = (typeLabels[row.questionType] ?? row.questionType).toLowerCase() const haystack = [ row.questionText, String(row.questionId), row.questionType, typeLabel, row.difficultyLevel, row.status, String(row.points), ] .join(" ") .toLowerCase() return haystack.includes(q) }) }, [questionsSorted, questionsSearch]) const questionsPageCount = Math.max(1, Math.ceil(filteredQuestions.length / questionsPageSize)) const safeQuestionsPage = Math.min(questionsPage, questionsPageCount) const paginatedQuestions = useMemo(() => { const start = (safeQuestionsPage - 1) * questionsPageSize return filteredQuestions.slice(start, start + questionsPageSize) }, [filteredQuestions, safeQuestionsPage, questionsPageSize]) const questionsStartEntry = filteredQuestions.length === 0 ? 0 : (safeQuestionsPage - 1) * questionsPageSize + 1 const questionsEndEntry = Math.min(safeQuestionsPage * questionsPageSize, filteredQuestions.length) useEffect(() => { setQuestionsPage(1) }, [questionsPageSize, setDetail?.id, questionsSearch]) const handleSaveSet = async () => { if (!setDetail) return if (!title.trim()) { toast.error("Title is required") return } setSavingSet(true) try { const updated = await savePlacementAssessmentSet(setDetail.id, { title: title.trim(), description: description.trim() || "PLACEMENT", status, shuffle_questions: shuffle, time_limit_minutes: timeLimit.trim() ? Number(timeLimit) : null, owner_type: "STANDALONE", owner_id: null, set_type: "INITIAL_ASSESSMENT", }) setSetDetail(updated) toast.success("Placement set saved") } catch (e) { notifyApiError(e, "Failed to save placement set") } finally { setSavingSet(false) } } const handlePublishToggle = async (nextPublished: boolean) => { if (!setDetail) return if (nextPublished && questions.length === 0) { toast.error("Add at least one question before publishing") setTab("questions") return } const publishedCount = questions.filter( (q) => String(q.status).toUpperCase() === "PUBLISHED", ).length if (nextPublished && publishedCount === 0) { toast.error("Publish at least one question before going live — draft questions are hidden from the app") setTab("questions") return } setSavingSet(true) try { const nextStatus = nextPublished ? "PUBLISHED" : "DRAFT" const updated = await savePlacementAssessmentSet(setDetail.id, { title: title.trim() || setDetail.title, description: description.trim() || "PLACEMENT", status: nextStatus, shuffle_questions: shuffle, time_limit_minutes: timeLimit.trim() ? Number(timeLimit) : null, owner_type: "STANDALONE", set_type: "INITIAL_ASSESSMENT", }) setSetDetail(updated) setStatus(nextStatus) toast.success(nextPublished ? "Placement assessment published" : "Placement assessment unpublished") } catch (e) { notifyApiError(e, "Failed to update publish status") } finally { setSavingSet(false) } } const closeQuestionForm = () => { setAddOpen(false) setEditingQuestionId(null) setEditingStatus("PUBLISHED") setDraft(emptyDraft()) setFormLoading(false) } const openCreateQuestion = () => { setEditingQuestionId(null) setEditingStatus("PUBLISHED") setDraft(emptyDraft()) setAddOpen(true) } const openEditQuestion = async (questionId: number) => { setEditingQuestionId(questionId) setDraft(emptyDraft()) setAddOpen(true) setFormLoading(true) try { const detail = await getPlacementQuestionDetail(questionId) const questionType = String(detail.question_type ?? "").toUpperCase() if (questionType !== "MCQ" && questionType !== "TRUE_FALSE") { toast.error("Only multiple choice and true/false questions can be edited here") closeQuestionForm() return } setEditingStatus( detail.status && detail.status !== "unassigned" ? detail.status : "DRAFT", ) setDraft(draftFromQuestionDetail(detail)) } catch (e) { notifyApiError(e, "Failed to load question") closeQuestionForm() } finally { setFormLoading(false) } } const validateDraft = (): string | null => { if (!draft.questionText.trim()) return "Question text is required" if (draft.points < 1) return "Points must be at least 1" const filled = draft.options.filter((o) => o.text.trim()) if (filled.length < 2) return "Add at least two options" if (!filled.some((o) => o.isCorrect)) return "Mark one correct option" return null } const buildQuestionPayload = () => ({ question_text: draft.questionText.trim(), question_type: draft.questionType, difficulty_level: draft.difficulty, points: draft.points, status: editingQuestionId != null ? editingStatus : "PUBLISHED", tips: draft.tips.trim() || undefined, explanation: draft.explanation.trim() || undefined, options: draft.options .filter((o) => o.text.trim()) .map((o, idx) => ({ option_order: idx + 1, option_text: o.text.trim(), is_correct: o.isCorrect, })), }) const handleSaveQuestion = async () => { if (!setDetail) return const error = validateDraft() if (error) { toast.error(error) return } setSavingQuestion(true) try { const payload = buildQuestionPayload() if (editingQuestionId != null) { await updateQuestion(editingQuestionId, payload) toast.success("Question updated") } else { await createAndAttachPlacementQuestion(setDetail.id, payload) toast.success("Question added to placement set") } closeQuestionForm() await loadQuestions(setDetail.id) await loadSet() } catch (e) { notifyApiError(e, editingQuestionId != null ? "Failed to update question" : "Failed to add question") } finally { setSavingQuestion(false) } } const handleRemoveQuestion = async (questionId: number) => { if (!setDetail) return setRemovingId(questionId) try { await detachPlacementQuestion(setDetail.id, questionId) toast.success("Question removed from placement set") await loadQuestions(setDetail.id) await loadSet() } catch (e) { notifyApiError(e, "Failed to remove question") } finally { setRemovingId(null) } } const handleToggleQuestionStatus = async (row: PlacementQuestionRow) => { const currentlyPublished = String(row.status).toUpperCase() === "PUBLISHED" const nextStatus = currentlyPublished ? "DRAFT" : "PUBLISHED" setStatusUpdatingId(row.questionId) try { const detail = await getPlacementQuestionDetail(row.questionId) const questionType = String(detail.question_type).toUpperCase() === "TRUE_FALSE" ? "TRUE_FALSE" : "MCQ" const difficulty = detail.difficulty_level === "MEDIUM" || detail.difficulty_level === "HARD" ? detail.difficulty_level : "EASY" const questionText = detail.question_text.trim() || row.questionText.trim() || `Question #${row.questionId}` await updateQuestion(row.questionId, { question_text: questionText, question_type: questionType, difficulty_level: difficulty, points: detail.points || row.points || 1, status: nextStatus, tips: detail.tips.trim() || undefined, explanation: detail.explanation.trim() || undefined, options: detail.options.length > 0 ? detail.options.map((o, idx) => ({ option_order: o.option_order || idx + 1, option_text: o.option_text, is_correct: o.is_correct, })) : undefined, }) setQuestions((prev) => prev.map((q) => q.questionId === row.questionId ? { ...q, status: nextStatus } : q, ), ) toast.success( nextStatus === "PUBLISHED" ? "Question published for the placement test" : "Question set to draft (hidden from the app)", ) } catch (e) { notifyApiError(e, "Failed to update question status") } finally { setStatusUpdatingId(null) } } if (loading) { return (
) } if (!setDetail) { return (

Could not load placement assessment

) } const published = status === "PUBLISHED" return (
Content

Initial placement assessment

Manage the single learner placement test, its questions, and the A1–C2 score thresholds used when grading submissions.

{published ? "Published" : "Draft"}
Live for learners void handlePublishToggle(!published)} disabled={savingSet} aria-label="Publish placement assessment" />
Questions
{setDetail.question_count ?? questions.length}
Total points
{totalPoints}
{( [ { id: "set", label: "Placement set" }, { id: "questions", label: "Questions" }, { id: "thresholds", label: "Score thresholds" }, ] as const ).map((item) => ( ))}
{tab === "set" && ( Placement set settings