/* eslint-disable @next/next/no-img-element */
import {MultipleChoiceExercise, MultipleChoiceQuestion} from "@/interfaces/exam";
import clsx from "clsx";
import {useState} from "react";
import {CommonProps} from ".";
import Button from "../Low/Button";

function Question({
	variant,
	prompt,
	solution,
	options,
	userSolution,
}: MultipleChoiceQuestion & {userSolution: string | undefined; onSelectOption?: (option: string) => void; showSolution?: boolean}) {
	const optionColor = (option: string) => {
		if (option === solution && !userSolution) {
			return "!border-mti-blue-light !text-mti-blue-light";
		}

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

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

	return (
		<div className="flex flex-col items-center gap-4">
			<span>{prompt}</span>
			<div className="grid grid-cols-4 gap-4 place-items-center">
				{variant === "image" &&
					options.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",
								optionColor(option.id),
							)}>
							<span className={clsx("text-sm", solution !== option.id && userSolution !== option.id && "opacity-50")}>{option.id}</span>
							<img src={option.src!} alt={`Option ${option.id}`} />
						</div>
					))}
				{variant === "text" &&
					options.map((option) => (
						<div
							key={option.id}
							className={clsx("flex border p-4 rounded-xl gap-2 cursor-pointer bg-white text-sm", optionColor(option.id))}>
							<span className="font-semibold">{option.id}.</span>
							<span>{option.text}</span>
						</div>
					))}
			</div>
		</div>
	);
}

export default function MultipleChoice({prompt, questions, userSolutions, onNext, onBack}: MultipleChoiceExercise & CommonProps) {
	const [questionIndex, setQuestionIndex] = useState(0);

	const next = () => {
		if (questionIndex === questions.length - 1) {
			onNext();
		} else {
			setQuestionIndex((prev) => prev + 1);
		}
	};

	const back = () => {
		if (questionIndex === 0) {
			onBack();
		} else {
			setQuestionIndex((prev) => prev - 1);
		}
	};

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

			<div className="self-end flex justify-between w-full gap-8 absolute bottom-8 left-0 px-8">
				<Button color="green" variant="outline" onClick={back} className="max-w-[200px] w-full">
					Back
				</Button>

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