/* eslint-disable @next/next/no-img-element */
import PracticeBadge from "@/components/Low/PracticeBadge";
import { MultipleChoiceQuestion } from "@/interfaces/exam";
import clsx from "clsx";
import reactStringReplace from "react-string-replace";
import { v4 } from "uuid";

interface Props {
    userSolution: string | undefined;
	onSelectOption?: (option: string) => void;
	showSolution?: boolean;
	isPractice?: boolean
}

const Question: React.FC<MultipleChoiceQuestion & Props> = ({
	id,
	variant,
	prompt,
	options,
	userSolution,
	onSelectOption,
	isPractice,
}) => {
	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 Question;
