import {infoButtonStyle} from "@/constants/buttonStyles";
import {WritingExam} from "@/interfaces/exam";
import clsx from "clsx";
import {Fragment, useEffect, useState} from "react";
import {toast} from "react-toastify";

interface Props {
	exam: WritingExam;
}

export default function Writing({exam}: Props) {
	const [inputText, setInputText] = useState("");
	const [isSubmitEnabled, setIsSubmitEnabled] = useState(false);
	const [timer, setTimer] = useState<number>();

	useEffect(() => {
		setTimer(exam.minTimer * 60);
		const timerInterval = setInterval(() => setTimer((prev) => prev && prev - 1), 1000);

		return () => {
			clearInterval(timerInterval);
		};
	}, [exam.minTimer]);

	useEffect(() => {
		const words = inputText.split(" ").filter((x) => x !== "");
		const {wordCounter} = exam.text;
		if (wordCounter.type === "min") {
			setIsSubmitEnabled(wordCounter.limit <= words.length);
		} else {
			setIsSubmitEnabled(true);
			if (wordCounter.limit < words.length) {
				toast.warning(`You have reached your word limit of ${wordCounter.limit} words!`);
				setInputText(words.slice(0, words.length - 1).join(" "));
			}
		}
	}, [inputText, exam]);

	return (
		<div className="h-full w-full flex flex-col items-center justify-center gap-8 relative">
			{timer && (
				<div className="absolute w-24 top-8 text-center right-8 font-semibold text-lg border-ielts-writing border-2 p-2 rounded-xl bg-ielts-writing-transparent text-white">
					{Math.floor(timer / 60) < 10 ? "0" : ""}
					{Math.floor(timer / 60)}:{timer % 60 < 10 ? "0" : ""}
					{timer % 60}
				</div>
			)}
			<div className="flex flex-col max-w-2xl gap-2">
				<span>{exam.text.info}</span>
				<span className="font-bold ml-8">
					{exam.text.prompt.split("\n").map((line, index) => (
						<Fragment key={index}>
							<span>{line}</span>
							<br />
						</Fragment>
					))}
				</span>
				<span>
					You should write {exam.text.wordCounter.type === "min" ? "at least" : "at most"} {exam.text.wordCounter.limit} words.
				</span>
			</div>
			<textarea
				className="w-1/2 h-1/3 cursor-text p-2 input input-bordered"
				onChange={(e) => setInputText(e.target.value)}
				value={inputText}
				placeholder="Write your text here..."
			/>
			<div className="w-1/2 flex justify-end">
				{!isSubmitEnabled && (
					<div className="tooltip" data-tip={`You have not yet reached your minimum word count of ${exam.text.wordCounter.limit} words!`}>
						<button className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)} disabled={!isSubmitEnabled}>
							Next
						</button>
					</div>
				)}
				{isSubmitEnabled && (
					<button className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)} disabled={!isSubmitEnabled}>
						Next
					</button>
				)}
			</div>
		</div>
	);
}
