/* 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";
import { v4 } from "uuid";
import PracticeBadge from "../Low/PracticeBadge";

function Question({
	id,
	variant,
	prompt,
	options,
	userSolution,
	onSelectOption,
	isPractice = false
}: MultipleChoiceQuestion & {
	userSolution: string | undefined;
	onSelectOption?: (option: string) => void;
	showSolution?: boolean;
	isPractice?: boolean
}) {
	const renderPrompt = (prompt: string) => {
		return reactStringReplace(prompt, /(<u>.*?<\/u>)/g, (match) => {
			const word = match.replaceAll("<u>", "").replaceAll("</u>", "");
			return word.length > 0 ? <u key={v4()}>{word}</u> : null;
		});
	};

	return (
		<div className="flex flex-col gap-8 relative">
			{isPractice && <PracticeBadge className="absolute -top-4 -right-12" />}
			{isNaN(Number(id)) ? (
				<span className={clsx("text-lg", isPractice && "text-mti-red")}>{renderPrompt(prompt).filter((x) => x?.toString() !== "<u>")}</span>
			) : (
				<span className={clsx("text-lg", isPractice && "text-mti-red")}>
					<>
						{id} - <span>{renderPrompt(prompt).filter((x) => x?.toString() !== "<u>")}</span>
					</>
				</span>
			)}
			<div className="flex flex-wrap gap-4 justify-between">
				{variant === "image" &&
					options.map((option) => (
						<div
							key={v4()}
							onClick={() => (onSelectOption ? onSelectOption(option.id.toString()) : null)}
							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",
								userSolution === option.id.toString() && "border-mti-purple-light",
							)}>
							<span key={v4()} className={clsx("text-sm", userSolution !== option.id.toString() && "opacity-50")}>
								{option.id.toString()}
							</span>
							<img src={option.src!} alt={`Option ${option.id.toString()}`} />
						</div>
					))}
				{variant === "text" &&
					options.map((option) => (
						<div
							key={v4()}
							onClick={() => (onSelectOption ? onSelectOption(option.id.toString()) : null)}
							className={clsx(
								"flex border p-4 rounded-xl gap-2 cursor-pointer bg-white text-base select-none",
								userSolution === option.id.toString() && "!bg-mti-purple-light !text-white",
							)}>
							<span className="font-semibold">{option.id.toString()}.</span>
							<span>{option.text}</span>
						</div>
					))}
			</div>
		</div>
	);
}

export default function MultipleChoice({
	id,
	prompt,
	type,
	questions,
	userSolutions,
	isPractice = false,
	onNext,
	onBack,
	disableProgressButtons = false
}: MultipleChoiceExercise & CommonProps) {
	const [answers, setAnswers] = useState<{ question: string; option: string }[]>(userSolutions || []);

	const { questionIndex, exerciseIndex, exam, shuffles, hasExamEnded, partIndex, setQuestionIndex, setCurrentSolution } = useExamStore(
		(state) => state,
	);

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

	const scrollToTop = () => Array.from(document.getElementsByTagName("body")).forEach((body) => body.scrollTo(0, 0));

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

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

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

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

	const calculateScore = () => {
		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 };
	};

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

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

	const back = () => {
		if (questionIndex === 0) {
			onBack({ exercise: id, solutions: answers, score: calculateScore(), type, shuffleMaps: shuffleMaps, isPractice });
		} else {
			if (exam?.module === "level" && typeof exam.parts[0].intro !== "undefined" && questionIndex === 0) return;
			setQuestionIndex(questionIndex - 2);
		}

		scrollToTop();
	};

	const progressButtons = () => (
		<div className="flex justify-between w-full gap-8">
			<Button
				color="purple"
				variant="outline"
				onClick={back}
				className="max-w-[200px] w-full"
				disabled={exam && exam.module === "level" && partIndex === 0 && questionIndex === 0}>
				Back
			</Button>

			<Button color="purple" onClick={next} className="max-w-[200px] self-end w-full">
				{exam &&
					exam.module === "level" &&
					partIndex === exam.parts.length - 1 &&
					exerciseIndex === exam.parts[partIndex].exercises.length - 1 &&
					questionIndex + 1 >= questions.length - 1
					? "Submit"
					: "Next"}
			</Button>
		</div>
	)

	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">
			{!disableProgressButtons && progressButtons()}

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

			{!disableProgressButtons && progressButtons()}
		</div>
	);
}
