import { MultipleChoiceExercise, MultipleChoiceQuestion, ShuffleMap } from "@/interfaces/exam";
import useExamStore, { usePersistentExamStore } from "@/stores/exam";
import clsx from "clsx";
import { useCallback, useEffect, useState } from "react";
import { CommonProps } from "../types";
import Question from "./Question";
import PracticeBadge from "../../Low/PracticeBadge";


const MultipleChoice: React.FC<MultipleChoiceExercise & CommonProps> = ({
	id,
	type,
	questions,
	userSolutions,
	isPractice = false,
	registerSolution,
	headerButtons,
	footerButtons,
	preview,
}) => {
	const [answers, setAnswers] = useState<{ question: string; option: string }[]>(userSolutions || []);

	const examState = useExamStore((state) => state);
	const persistentExamState = usePersistentExamStore((state) => state);

	const { questionIndex, shuffles } = !preview ? examState : persistentExamState;

	const shuffleMaps = shuffles.find((x) => x.exerciseID == id)?.shuffles;

	const onSelectOption = (option: string, question: MultipleChoiceQuestion) => {
		setAnswers((prev) => [...prev.filter((x) => x.question !== question.id), { option, question: question.id }]);
	};

	const getShuffledSolution = (originalSolution: string, questionShuffleMap: ShuffleMap) => {
		for (const [newPosition, originalPosition] of Object.entries(questionShuffleMap.map)) {
			if (originalPosition === originalSolution) {
				return newPosition;
			}
		}
		return originalSolution;
	};

	const calculateScore = useCallback(() => {
		const total = questions.length;
		const correct = answers.filter((x) => {
			const matchingQuestion = questions.find((y) => {
				return y.id.toString() === x.question.toString();
			});

			let isSolutionCorrect;
			if (!shuffleMaps) {
				isSolutionCorrect = matchingQuestion?.solution === x.option;
			} else {
				const shuffleMap = shuffleMaps.find((map) => map.questionID == x.question);
				if (shuffleMap) {
					isSolutionCorrect = getShuffledSolution(x.option, shuffleMap) == matchingQuestion?.solution;
				} else {
					isSolutionCorrect = matchingQuestion?.solution === x.option;
				}
			}
			return isSolutionCorrect || false;
		}).length;
		const missing = total - answers!.filter((x) => questions.find((y) => x.question.toString() === y.id.toString())).length;
		return { total, correct, missing };
	}, [answers, questions, shuffleMaps]);

	useEffect(() => {
		registerSolution(() => ({
			exercise: id,
			solutions: answers,
			score: calculateScore(),
			shuffleMaps,
			type,
			isPractice
		}));
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [id, answers, type, isPractice, shuffleMaps, calculateScore]);

	const renderAllQuestions = () =>
		questions.map(question => (
			<div
				key={question.id} className="flex flex-col gap-8 h-fit w-full bg-mti-gray-smoke rounded-xl px-16 py-8">
				<Question
					{...question}
					isPractice={isPractice}
					userSolution={answers.find((x) => question.id === x.question)?.option}
					onSelectOption={(option) => onSelectOption(option, question)}
				/>
			</div>
		))

	const renderTwoQuestions = () => (
		<>
			<div className="flex flex-col gap-8 h-fit w-full bg-mti-gray-smoke rounded-xl px-16 py-8">
				{questionIndex < questions.length && (
					<Question
						{...questions[questionIndex]}
						isPractice={isPractice}
						userSolution={answers.find((x) => questions[questionIndex].id === x.question)?.option}
						onSelectOption={(option) => onSelectOption(option, questions[questionIndex])}
					/>
				)}
			</div>

			{questionIndex + 1 < questions.length && (
				<div className="flex flex-col gap-8 h-fit w-full bg-mti-gray-smoke rounded-xl px-16 py-8">
					<Question
						{...questions[questionIndex + 1]}
						isPractice={isPractice}
						userSolution={answers.find((x) => questions[questionIndex + 1].id === x.question)?.option}
						onSelectOption={(option) => onSelectOption(option, questions[questionIndex + 1])}
					/>
				</div>
			)}
		</>
	)

	return (
		<div className="flex flex-col gap-4">
			{headerButtons}
			<div className={clsx("flex flex-col gap-4 mt-4", (headerButtons && footerButtons) && "mb-20")}>
				{(!headerButtons && !footerButtons) ? renderAllQuestions() : renderTwoQuestions()}
			</div>
			{footerButtons}
		</div>
	);
}

export default MultipleChoice;
