import {FillBlanksExercise} from "@/interfaces/exam";
import useExamStore from "@/stores/examStore";
import clsx from "clsx";
import {Fragment, useEffect, useState} from "react";
import reactStringReplace from "react-string-replace";
import {CommonProps} from ".";
import Button from "../Low/Button";

interface WordsDrawerProps {
	words: {word: string; isDisabled: boolean}[];
	isOpen: boolean;
	blankId?: string;
	previouslySelectedWord?: string;
	onCancel: () => void;
	onAnswer: (answer: string) => void;
}

function WordsDrawer({words, isOpen, blankId, previouslySelectedWord, onCancel, onAnswer}: WordsDrawerProps) {
	const [selectedWord, setSelectedWord] = useState<string | undefined>(previouslySelectedWord);

	return (
		<>
			<div
				className={clsx(
					"w-full h-full absolute top-0 left-0 bg-gradient-to-t from-mti-black to-transparent z-10",
					isOpen ? "visible opacity-10" : "invisible opacity-0",
				)}
			/>
			<div
				className={clsx(
					"absolute w-full bg-white px-7 py-8 bottom-0 left-0 shadow-2xl rounded-2xl z-20 flex flex-col gap-8 transition-opacity duration-300 ease-in-out",
					isOpen ? "visible opacity-100" : "invisible opacity-0",
				)}>
				<div className="w-full flex gap-2">
					<div className="rounded-full w-6 h-6 flex items-center justify-center text-white bg-mti-purple-light">{blankId}</div>
					<span> Choose the correct word:</span>
				</div>
				<div className="grid grid-cols-6 gap-6" key="word-array">
					{words.map(({word, isDisabled}) => (
						<button
							key={`${word}_${blankId}`}
							onClick={() => setSelectedWord((prev) => (prev === word ? undefined : word))}
							className={clsx(
								"rounded-full py-3 text-center transition duration-300 ease-in-out",
								selectedWord === word ? "text-white bg-mti-purple-light" : "bg-mti-purple-ultralight",
								!isDisabled && "hover:text-white hover:bg-mti-purple",
								"disabled:cursor-not-allowed disabled:text-mti-gray-dim",
							)}
							disabled={isDisabled}>
							{word}
						</button>
					))}
				</div>
				<div className="flex justify-between w-full">
					<Button color="purple" variant="outline" className="max-w-[200px] w-full" onClick={onCancel}>
						Back
					</Button>
					<Button color="purple" className="max-w-[200px] w-full" onClick={() => onAnswer(selectedWord!)} disabled={!selectedWord}>
						Confirm
					</Button>
				</div>
			</div>
		</>
	);
}

export default function FillBlanks({
	id,
	allowRepetition,
	type,
	prompt,
	solutions,
	text,
	words,
	userSolutions,
	onNext,
	onBack,
}: FillBlanksExercise & CommonProps) {
	const [answers, setAnswers] = useState<{id: string; solution: string}[]>(userSolutions);
	const [currentBlankId, setCurrentBlankId] = useState<string>();
	const [isDrawerShowing, setIsDrawerShowing] = useState(false);

	const hasExamEnded = useExamStore((state) => state.hasExamEnded);
	const allBlanks = Array.from(text.match(/({{\d+}})/g) || []).map((x) => x.replaceAll("{", "").replaceAll("}", ""));

	useEffect(() => {
		setTimeout(() => setIsDrawerShowing(!!currentBlankId), 100);
	}, [currentBlankId]);

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

	const calculateScore = () => {
		const total = text.match(/({{\d+}})/g)?.length || 0;
		const correct = answers.filter(
			(x) => solutions.find((y) => x.id.toString() === y.id.toString())?.solution === x.solution.toLowerCase() || false,
		).length;
		const missing = total - answers.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, "");
					const userSolution = answers.find((x) => x.id === id);

					return (
						<button
							className={clsx(
								"rounded-full hover:text-white hover:bg-mti-purple transition duration-300 ease-in-out my-1",
								!userSolution && "w-6 h-6 text-center text-mti-purple-light bg-mti-purple-ultralight",
								currentBlankId === id && "text-white !bg-mti-purple-light ",
								userSolution && "px-5 py-2 text-center text-white bg-mti-purple-light",
							)}
							onClick={() => setCurrentBlankId(id)}>
							{userSolution ? userSolution.solution : id}
						</button>
					);
				})}
			</span>
		);
	};

	return (
		<>
			<div className="flex flex-col gap-4 mt-4 h-full mb-20">
				{(!!currentBlankId || isDrawerShowing) && (
					<WordsDrawer
						key={currentBlankId}
						blankId={currentBlankId}
						words={words.map((word) => ({word, isDisabled: allowRepetition ? false : answers.map((x) => x.solution).includes(word)}))}
						previouslySelectedWord={currentBlankId ? answers.find((x) => x.id === currentBlankId)?.solution : undefined}
						isOpen={isDrawerShowing}
						onCancel={() => setCurrentBlankId(undefined)}
						onAnswer={(solution: string) => {
							setAnswers((prev) => [...prev.filter((x) => x.id !== currentBlankId), {id: currentBlankId!, solution}]);
							if (allBlanks.findIndex((x) => x === currentBlankId) + 1 < allBlanks.length) {
								setCurrentBlankId(allBlanks[allBlanks.findIndex((x) => x === currentBlankId) + 1]);
								return;
							}
							setCurrentBlankId(undefined);
						}}
					/>
				)}
				<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">
					{text.split("\\n").map((line, index) => (
						<p key={index}>
							{renderLines(line)}
							<br />
						</p>
					))}
				</span>
			</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: answers, score: calculateScore(), type})}
					className="max-w-[200px] w-full">
					Back
				</Button>

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