import {errorButtonStyle, infoButtonStyle} from "@/constants/buttonStyles";
import {FillBlanksExercise} from "@/interfaces/exam";
import {mdiArrowLeft, mdiArrowRight} from "@mdi/js";
import Icon from "@mdi/react";
import clsx from "clsx";
import reactStringReplace from "react-string-replace";
import {CommonProps} from ".";
import {Fragment} from "react";

export default function FillBlanksSolutions({prompt, solutions, text, userSolutions, onNext, onBack}: FillBlanksExercise & CommonProps) {
	const renderLines = (line: string) => {
		return (
			<span>
				{reactStringReplace(line, /({{\d}})/g, (match) => {
					const id = match.replaceAll(/[\{\}]/g, "");
					const userSolution = userSolutions.find((x) => x.id === id);
					const solution = solutions.find((x) => x.id === id)!;

					if (!userSolution) {
						return (
							<>
								<button className={clsx("border-2 rounded-xl px-4 text-gray-500 border-gray-500 my-2")}>{solution.solution}</button>
							</>
						);
					}

					if (userSolution.solution === solution.solution) {
						return <button className={clsx("border-2 rounded-xl px-4 text-green-500 border-green-500 my-2")}>{solution.solution}</button>;
					}

					if (userSolution.solution !== solution.solution) {
						return (
							<>
								<button className={clsx("border-2 rounded-xl px-4 text-red-500 border-red-500 mr-1 my-2")}>
									{userSolution.solution}
								</button>
								<button className={clsx("border-2 rounded-xl px-4 text-green-400 border-green-400 my-2")}>{solution.solution}</button>
							</>
						);
					}
				})}
			</span>
		);
	};

	return (
		<>
			<div className="flex flex-col gap-4">
				<span className="text-base md:text-lg font-medium text-center px-2 md:px-4 lg:px-48">
					{prompt.split("\\n").map((line, index) => (
						<Fragment key={index}>
							{line}
							<br />
						</Fragment>
					))}
				</span>
				<span>
					{text.split("\\n").map((line, index) => (
						<Fragment key={index}>
							{renderLines(line)}
							<br />
						</Fragment>
					))}
				</span>
			</div>

			<div className="self-end flex flex-col-reverse items-center w-full md:justify-between md:items-start md:flex-row gap-8">
				<button className={clsx("btn btn-wide gap-4 relative text-white", errorButtonStyle)} onClick={onBack}>
					<div className="absolute left-4">
						<Icon path={mdiArrowLeft} color="white" size={1} />
					</div>
					Back
				</button>
				<button className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)} onClick={onNext}>
					Next
					<div className="absolute right-4">
						<Icon path={mdiArrowRight} color="white" size={1} />
					</div>
				</button>
			</div>
		</>
	);
}
