import { Button } from '@/components/ui/button'; import { Label } from '@/components/ui/label'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { useEffect, useMemo, useState } from 'react'; interface Props { question: ExamQuestion; answer: any; onAnswerChange: (answer: any) => void; } const MatchingQuestion = ({ question, answer, onAnswerChange }: Props) => { const matches = question.options?.matches || []; const buildInitialMatches = () => { if (Array.isArray(answer?.matches)) { const arrayMatches = answer.matches as Array<{ id: number; answer: string }>; return arrayMatches.reduce>((acc, item) => { acc[item.id] = item.answer; return acc; }, {}); } if (answer?.matches && typeof answer.matches === 'object') { return { ...(answer.matches as Record) }; } return {}; }; const [selectedMatches, setSelectedMatches] = useState>(buildInitialMatches); useEffect(() => { setSelectedMatches(buildInitialMatches()); // eslint-disable-next-line react-hooks/exhaustive-deps }, [question.id]); const emitChange = (newMatches: Record) => { setSelectedMatches(newMatches); const formatted = Object.entries(newMatches).map(([id, value]) => ({ id: Number(id), answer: value, })); onAnswerChange({ matches: formatted, }); }; const handleMatch = (leftId: number, answerValue: string) => { emitChange({ ...selectedMatches, [leftId]: answerValue, }); }; const handleClearAll = () => { emitChange({}); }; const leftItems = useMemo(() => matches.map((pair: any) => ({ id: pair.id, text: pair.question })), [matches]); const rightItems = useMemo(() => matches.map((pair: any) => ({ id: pair.id, text: pair.answer })), [matches]); const shuffledRightItems = useMemo(() => [...rightItems].sort(() => Math.random() - 0.5), [rightItems]); return (

Match each item on the left with the correct item on the right:

{leftItems.map((leftItem) => (
))}
{Object.keys(selectedMatches).length > 0 && (

Matched: {Object.keys(selectedMatches).length} of {leftItems.length}

)}
); }; export default MatchingQuestion;