import Button from "@/components/Low/Button";
import Modal from "@/components/Modal";
import { Exam, LevelExam, MultipleChoiceExercise, ShuffleMap } from "@/interfaces/exam";
import useExamStore, { usePersistentExamStore } from "@/stores/exam";
import { defaultExamUserSolutions } from "@/utils/exams";
import clsx from "clsx";
import { useEffect, useMemo, useState } from "react";
import { BsFillGrid3X3GapFill } from "react-icons/bs";

interface Props {
	exam: LevelExam
	showSolutions: boolean;
	runOnClick: ((index: number) => void) | undefined;
	preview: boolean,
}

const MCQuestionGrid: React.FC<Props> = ({ exam, showSolutions, runOnClick, preview }) => {
	const [isOpen, setIsOpen] = useState(false);

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

	const {
		userSolutions,
		partIndex: sectionIndex,
		exerciseIndex,
	} = !preview ? examState : persistentExamState;

	const currentExercise = useMemo(() => (exam as LevelExam).parts[sectionIndex!].exercises[exerciseIndex] as MultipleChoiceExercise, [exam, exerciseIndex, sectionIndex])
	const userSolution = useMemo(() => userSolutions!.find((x) => x.exercise.toString() == currentExercise.id.toString())!, [currentExercise.id, userSolutions])
	const answeredQuestions = useMemo(() =>
		userSolution ? new Set(userSolution.solutions.map(sol => sol.question.toString())) : new Set(),
		[userSolution]
	);
	const exerciseOffset = useMemo(() => Number(currentExercise.questions[0].id), [currentExercise.questions])
	const lastExercise = useMemo(() => exerciseOffset + (currentExercise.questions.length - 1),
		[currentExercise.questions.length, exerciseOffset]);

	const getQuestionColor = (questionId: string, solution: string, userQuestionSolution: string | undefined) => {
		const questionShuffleMap = userSolutions.reduce((foundMap, userSolution) => {
			if (foundMap) return foundMap;
			return userSolution.shuffleMaps?.find(map => map.questionID.toString() === questionId.toString()) || null;
		}, null as ShuffleMap | null);
		const newSolution = questionShuffleMap ? questionShuffleMap?.map[solution] : solution;

		if (!userSolutions) return "";

		if (!userQuestionSolution) {
			return "!bg-mti-gray-davy !border--mti-gray-davy !text-mti-gray-davy !text-white hover:!bg-gray-700";
		}

		return userQuestionSolution === newSolution ?
			"!bg-mti-purple-light !text-mti-purple-light !text-white hover:!bg-mti-purple-dark" :
			"!bg-mti-rose-light !border-mti-rose-light !text-mti-rose-light !text-white hover:!bg-mti-rose-dark";
	}

	return (
		<>
			<Button variant="outline" onClick={() => setIsOpen(true)} padding="p-2" className="rounded-lg">
				<BsFillGrid3X3GapFill size={24} />
			</Button>
			<Modal
				isOpen={isOpen}
				onClose={() => setIsOpen(false)}
				className="w-full max-w-md transform overflow-hidden rounded-2xl bg-white shadow-xl transition-all"
			>
				<>
					<h3 className="text-xl font-semibold mb-4 text-center">{`Part ${sectionIndex + 1} (Questions ${exerciseOffset} - ${lastExercise})`}</h3>
					<div className="grid grid-cols-5 gap-3 px-4 py-2">
						{currentExercise.questions.map((_, index) => {
							const questionNumber = exerciseOffset + index;
							const isAnswered = answeredQuestions.has(questionNumber.toString());
							const solution = currentExercise.questions.find((x) => x.id.toString() == questionNumber.toString())!.solution;

							const userQuestionSolution = currentExercise.userSolutions?.find((x) => x.question.toString() == questionNumber.toString())?.option;
							return (
								<Button
									variant={showSolutions ? "solid" : (isAnswered ? "solid" : "outline")}
									key={index}
									className={clsx(
										"w-12 h-12 flex items-center justify-center rounded-lg text-sm font-bold transition-all duration-200 ease-in-out",
										(showSolutions ?
											getQuestionColor(questionNumber.toString(), solution, userQuestionSolution) :
											(isAnswered ?
												"bg-mti-purple-light border-mti-purple-light text-white hover:bg-mti-purple-dark hover:border-mti-purple-dark" :
												"bg-white border-gray-400 hover:bg-gray-100 hover:text-gray-700"
											)
										)
									)}
									onClick={() => { if (typeof runOnClick !== "undefined") { runOnClick(index); } setIsOpen(false); }}
								>
									{questionNumber}
								</Button>
							);
						})}
					</div>
					<p className="mt-4 text-sm text-gray-600 text-center">
						Click a question number to jump to that question
					</p>
				</>
			</Modal>
		</>
	);
}

export default MCQuestionGrid;
