import {errorButtonStyle, infoButtonStyle} from "@/constants/buttonStyles";
import {WriteBlanksExercise} from "@/interfaces/exam";
import {mdiArrowLeft, mdiArrowRight} from "@mdi/js";
import Icon from "@mdi/react";
import clsx from "clsx";
import {Fragment, useEffect, useState} from "react";
import reactStringReplace from "react-string-replace";
import {CommonProps} from ".";
import {toast} from "react-toastify";
import Button from "../Low/Button";

function Blank({
	id,
	maxWords,
	solutions,
	userSolution,
	disabled = false,
	setUserSolution,
}: {
	id: string;
	solutions: string[];
	userSolution?: string;
	maxWords: number;
	disabled?: boolean;
	setUserSolution?: (solution: string) => void;
}) {
	const [userInput, setUserInput] = useState(userSolution || "");

	useEffect(() => {
		const words = userInput.split(" ").filter((x) => x !== "");
		if (words.length >= maxWords) {
			setUserInput(words.join(" ").trim());
			if (setUserSolution) setUserSolution(words.join(" ").trim());
		}
	}, [maxWords, userInput, setUserSolution]);

	const isUserSolutionCorrect = () => userSolution && solutions.map((x) => x.trim().toLowerCase()).includes(userSolution.trim().toLowerCase());

	const getSolutionStyling = () => {
		if (!userSolution) {
			return "bg-mti-gray-davy text-white";
		}

		return "bg-mti-purple-ultralight text-mti-purple-light";
	};

	return (
		<span className="inline-flex gap-2 ml-2">
			{userSolution && !isUserSolutionCorrect() && (
				<div
					className="py-2 px-3 rounded-2xl w-fit focus:outline-none my-2 bg-mti-rose-ultralight text-mti-rose-light"
					contentEditable={disabled}>
					{userSolution}
				</div>
			)}
			<div className={clsx("py-2 px-3 rounded-2xl w-fit focus:outline-none my-2", getSolutionStyling())} contentEditable={disabled}>
				{!solutions ? userInput : solutions.join(" / ")}
			</div>
		</span>
	);
}

export default function WriteBlanksSolutions({
	id,
	type,
	prompt,
	maxWords,
	solutions,
	userSolutions,
	text,
	onNext,
	onBack,
}: WriteBlanksExercise & CommonProps) {
	const calculateScore = () => {
		const total = text.match(/({{\d+}})/g)?.length || 0;
		const correct = userSolutions.filter(
			(x) =>
				solutions
					.find((y) => x.id.toString() === y.id.toString())
					?.solution.map((y) => y.toLowerCase().trim())
					.includes(x.solution.toLowerCase().trim()) || false,
		).length;
		const missing = total - userSolutions.filter((x) => solutions.find((y) => x.id.toString() === y.id.toString())).length;

		return {total, correct, missing};
	};

	const renderLines = (line: string) => {
		return (
			<span className="text-base leading-5">
				{reactStringReplace(line, /({{\d+}})/g, (match) => {
					const id = match.replaceAll(/[\{\}]/g, "").toString();
					const userSolution = userSolutions.find((x) => x.id.toString() === id.toString());
					const solution = solutions.find((x) => x.id.toString() === id.toString())!;

					return (
						<Blank userSolution={userSolution?.solution} maxWords={maxWords} id={id.toString()} solutions={solution.solution} disabled />
					);
				})}
			</span>
		);
	};

	return (
		<>
			<div className="flex flex-col gap-4 mt-4 h-full w-full mb-20">
				<span className="text-sm w-full leading-6">
					{prompt.split("\\n").map((line, index) => (
						<Fragment key={index}>
							{line}
							<br />
						</Fragment>
					))}
				</span>
				<span className="bg-mti-gray-smoke rounded-xl px-5 py-6">
					{userSolutions &&
						text.split("\\n").map((line, index) => (
							<p key={index}>
								{renderLines(line)}
								<br />
							</p>
						))}
				</span>
				<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={() => onBack({exercise: id, solutions: userSolutions, score: calculateScore(), type})}
					className="max-w-[200px] w-full">
					Back
				</Button>

				<Button
					color="purple"
					onClick={() => onNext({exercise: id, solutions: userSolutions, score: calculateScore(), type})}
					className="max-w-[200px] self-end w-full">
					Next
				</Button>
			</div>
		</>
	);
}
