/* eslint-disable @next/next/no-img-element */
import { MultipleChoiceExercise, MultipleChoiceQuestion, ShuffleMap } from "@/interfaces/exam";
import useExamStore from "@/stores/examStore";
import clsx from "clsx";
import { useEffect, useState } from "react";
import reactStringReplace from "react-string-replace";
import { CommonProps } from ".";
import Button from "../Low/Button";

function Question({
	id,
	variant,
	prompt,
	solution,
	options,
	userSolution,
}: MultipleChoiceQuestion & { userSolution: string | undefined; onSelectOption?: (option: string) => void; showSolution?: boolean }) {
	const { userSolutions } = useExamStore((state) => state);

	const getShuffledOptions = (options: { id: string, text: string }[], questionShuffleMap: ShuffleMap) => {
		const shuffledOptions = ['A', 'B', 'C', 'D'].map(newId => {
			const originalId = questionShuffleMap.map[newId];
			const originalOption = options.find(option => option.id === originalId);
			return {
				id: newId,
				text: originalOption!.text
			};
		});
		return shuffledOptions;
	}

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

	const questionShuffleMap = userSolutions.reduce((foundMap, userSolution) => {
		if (foundMap) return foundMap;
		return userSolution.shuffleMaps?.find(map => map.id === id) || null;
	}, null as ShuffleMap | null);

	const questionOptions = questionShuffleMap ? getShuffledOptions(options as { id: string, text: string }[], questionShuffleMap) : options;
	const newSolution = questionShuffleMap ? getShuffledSolution(solution, questionShuffleMap) : solution;

	const renderPrompt = (prompt: string) => {
		return reactStringReplace(prompt, /(<u>.*?<\/u>)/g, (match) => {
			const word = match.replaceAll("<u>", "").replaceAll("</u>", "");
			return word.length > 0 ? <u>{word}</u> : null;
		});
	};

	const optionColor = (option: string) => {
		if (option === newSolution && !userSolution) {
			return "!border-mti-gray-davy !text-mti-gray-davy";
		}

		if (option === newSolution) {
			return "!border-mti-purple-light !text-mti-purple-light";
		}

		return userSolution === option ? "!border-mti-rose-light !text-mti-rose-light" : "";
	};

	return (
		<div className="flex flex-col gap-4">
			{isNaN(Number(id)) ? (
				<span>{renderPrompt(prompt).filter((x) => x?.toString() !== "<u>")} </span>
			) : (
				<span className="text-lg">
					<>
						{id} - <span className="text-lg">{renderPrompt(prompt).filter((x) => x?.toString() !== "<u>")} </span>
					</>
				</span>
			)}
			<div className="flex flex-wrap gap-4 justify-between">
				{variant === "image" &&
					questionOptions.map((option) => (
						<div
							key={option?.id}
							className={clsx(
								"flex flex-col items-center border border-mti-gray-platinum p-4 px-8 rounded-xl gap-4 cursor-pointer bg-white relative select-none",
								optionColor(option!.id),
							)}>
							<span className={clsx("text-sm", newSolution !== option?.id && userSolution !== option?.id && "opacity-50")}>{option?.id}</span>
							{"src" in option && <img src={option?.src!} alt={`Option ${option?.id}`} />}
						</div>
					))}
				{variant === "text" &&
					questionOptions.map((option) => (
						<div
							key={option?.id}
							className={clsx("flex border p-4 rounded-xl gap-2 cursor-pointer bg-white text-base select-none", optionColor(option!.id))}>
							<span className="font-semibold">{option?.id}.</span>
							<span>{option?.text}</span>
						</div>
					))}
			</div>
		</div>
	);
}

export default function MultipleChoice({ id, type, prompt, questions, userSolutions, onNext, onBack }: MultipleChoiceExercise & CommonProps) {
	const { questionIndex, setQuestionIndex, partIndex, exam } = useExamStore((state) => state);


	const calculateScore = () => {
		const total = questions.length;
		const correct = userSolutions.filter(
			(x) => questions.find((y) => y.id.toString() === x.question.toString())?.solution === x.option || false,
		).length;
		const missing = total - userSolutions.filter((x) => questions.find((y) => y.id.toString() === x.question.toString())).length;

		return { total, correct, missing };
	};

	const next = () => {
		if (questionIndex === questions.length - 1) {
			onNext({ exercise: id, solutions: userSolutions, score: calculateScore(), type });
		} else {
			setQuestionIndex(questionIndex + 1);
		}
	};

	const back = () => {
		if (questionIndex === 0) {
			onBack({ exercise: id, solutions: userSolutions, score: calculateScore(), type });
		} else {
			setQuestionIndex(questionIndex - 1);
		}
	};

	return (
		<>
			<div className="flex flex-col gap-4 w-full h-full mb-20">
				<div className="flex flex-col gap-2 mt-4 h-full bg-mti-gray-smoke rounded-xl px-16 py-8">
					{/*<span className="text-xl font-semibold">{prompt}</span>*/}
					{userSolutions && questionIndex < questions.length && (
						<Question
							{...questions[questionIndex]}
							userSolution={userSolutions.find((x) => questions[questionIndex].id === x.question)?.option}
						/>
					)}
				</div>
				<div className="flex gap-4 items-center">
					<div className="flex gap-2 items-center">
						<div className="w-4 h-4 rounded-full bg-mti-purple" />
						Correct
					</div>
					<div className="flex gap-2 items-center">
						<div className="w-4 h-4 rounded-full bg-mti-gray-davy" />
						Unanswered
					</div>
					<div className="flex gap-2 items-center">
						<div className="w-4 h-4 rounded-full bg-mti-rose" />
						Wrong
					</div>
				</div>
			</div>		

			<div className="self-end flex justify-between w-full gap-8 absolute bottom-8 left-0 px-8">
				<Button color="purple" variant="outline" onClick={back} className="max-w-[200px] w-full"
					disabled={
						exam && typeof partIndex !== "undefined" && exam.module === "level" && 
						typeof exam.parts[0].intro === "string" && questionIndex === 0 && partIndex === 0}
				>
					Back
				</Button>

				<Button color="purple" onClick={next} className="max-w-[200px] self-end w-full">
					Next
				</Button>
			</div>
		</>
	);
}
