import Input from "@/components/Low/Input";
import {WritingExam, WritingExercise} from "@/interfaces/exam";
import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams";
import {playSound} from "@/utils/sound";
import {Tab} from "@headlessui/react";
import axios from "axios";
import clsx from "clsx";
import {useRouter} from "next/router";
import {useEffect, useState} from "react";
import {BsArrowRepeat, BsCheck} from "react-icons/bs";
import {toast} from "react-toastify";
import {v4} from "uuid";

const TaskTab = ({task, index, setTask}: {task?: string; index: number; setTask: (task: string) => void}) => {
	const [isLoading, setIsLoading] = useState(false);

	const generate = () => {
		setIsLoading(true);
		axios
			.get(`/api/exam/writing/generate/writing_task${index}_general`)
			.then((result) => {
				playSound(typeof result.data === "string" ? "error" : "check");
				if (typeof result.data === "string") return toast.error("Something went wrong, please try to generate again.");
				setTask(result.data.question);
			})
			.catch((error) => {
				console.log(error);
				toast.error("Something went wrong!");
			})
			.finally(() => setIsLoading(false));
	};

	return (
		<Tab.Panel className="w-full bg-ielts-writing/20 min-h-[600px] h-full rounded-xl p-6 flex flex-col gap-4">
			<div className="flex gap-4 items-end">
				<button
					onClick={generate}
					disabled={isLoading}
					className={clsx(
						"bg-ielts-writing/70 border border-ielts-writing text-white w-full px-6 py-6 rounded-xl h-[70px]",
						"hover:bg-ielts-writing disabled:bg-ielts-writing/40 disabled:cursor-not-allowed",
						"transition ease-in-out duration-300",
					)}>
					{isLoading ? (
						<div className="flex items-center justify-center">
							<BsArrowRepeat className="text-white animate-spin" size={25} />
						</div>
					) : (
						"Generate"
					)}
				</button>
			</div>
			{isLoading && (
				<div className="w-fit h-fit mt-12 self-center animate-pulse flex flex-col gap-8 items-center">
					<span className={clsx("loading loading-infinity w-32 text-ielts-writing")} />
					<span className={clsx("font-bold text-2xl text-ielts-writing")}>Generating...</span>
				</div>
			)}
			{task && (
				<div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide">
					<span className="w-full h-96">{task}</span>
				</div>
			)}
		</Tab.Panel>
	);
};

const WritingGeneration = () => {
	const [task1, setTask1] = useState<string>();
	const [task2, setTask2] = useState<string>();
	const [minTimer, setMinTimer] = useState(60);
	const [isLoading, setIsLoading] = useState(false);
	const [resultingExam, setResultingExam] = useState<WritingExam>();

	useEffect(() => {
		const task1Timer = task1 ? 20 : 0;
		const task2Timer = task2 ? 40 : 0;
		setMinTimer(task1Timer > 0 || task2Timer > 0 ? task1Timer + task2Timer : 20);
	}, [task1, task2]);

	const router = useRouter();

	const setExams = useExamStore((state) => state.setExams);
	const setSelectedModules = useExamStore((state) => state.setSelectedModules);

	const loadExam = async (examId: string) => {
		const exam = await getExamById("writing", examId.trim());
		if (!exam) {
			toast.error("Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID", {
				toastId: "invalid-exam-id",
			});

			return;
		}

		setExams([exam]);
		setSelectedModules(["writing"]);

		router.push("/exercises");
	};

	const submitExam = () => {
		if (!task1 && !task2) {
			toast.error("Please generate a task before submitting");
			return;
		}

		const exercise1 = task1
			? ({
					id: v4(),
					type: "writing",
					prefix: `You should spend about 20 minutes on this task.`,
					prompt: task1,
					userSolutions: [],
					suffix: "You should write at least 150 words.",
					wordCounter: {
						limit: 150,
						type: "min",
					},
			  } as WritingExercise)
			: undefined;

		const exercise2 = task2
			? ({
					id: v4(),
					type: "writing",
					prefix: `You should spend about 40 minutes on this task.`,
					prompt: task2,
					userSolutions: [],
					suffix: "You should write at least 250 words.",
					wordCounter: {
						limit: 250,
						type: "min",
					},
			  } as WritingExercise)
			: undefined;

		setIsLoading(true);
		const exam: WritingExam = {
			isDiagnostic: false,
			minTimer,
			module: "writing",
			exercises: [...(exercise1 ? [exercise1] : []), ...(exercise2 ? [exercise2] : [])],
			id: v4(),
			variant: exercise1 && exercise2 ? "full" : "partial",
		};

		axios
			.post(`/api/exam/writing`, exam)
			.then((result) => {
				console.log(`Generated Exam ID: ${result.data.id}`);
				playSound("sent");
				toast.success("This new exam has been generated successfully! Check the ID in our browser's console.");
				setResultingExam(result.data);

				setTask1(undefined);
				setTask2(undefined);
			})
			.catch((error) => {
				console.log(error);
				toast.error("Something went wrong while generating, please try again later.");
			})
			.finally(() => setIsLoading(false));
	};

	return (
		<>
			<div className="flex flex-col gap-3">
				<label className="font-normal text-base text-mti-gray-dim">Timer</label>
				<Input
					type="number"
					name="minTimer"
					onChange={(e) => setMinTimer(parseInt(e) < 15 ? 15 : parseInt(e))}
					value={minTimer}
					className="max-w-[300px]"
				/>
			</div>

			<Tab.Group>
				<Tab.List className="flex space-x-1 rounded-xl bg-ielts-writing/20 p-1">
					<Tab
						className={({selected}) =>
							clsx(
								"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-writing/70 flex gap-2 items-center justify-center",
								"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-writing focus:outline-none focus:ring-2",
								"transition duration-300 ease-in-out",
								selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-writing",
							)
						}>
						Task 1 {task1 && <BsCheck />}
					</Tab>
					<Tab
						className={({selected}) =>
							clsx(
								"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-writing/70 flex gap-2 items-center justify-center",
								"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-writing focus:outline-none focus:ring-2",
								"transition duration-300 ease-in-out",
								selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-writing",
							)
						}>
						Task 2 {task2 && <BsCheck />}
					</Tab>
				</Tab.List>
				<Tab.Panels>
					{[
						{task: task1, setTask: setTask1},
						{task: task2, setTask: setTask2},
					].map(({task, setTask}, index) => (
						<TaskTab task={task} index={index + 1} key={index} setTask={setTask} />
					))}
				</Tab.Panels>
			</Tab.Group>
			<div className="w-full flex justify-end gap-4">
				{resultingExam && (
					<button
						disabled={isLoading}
						onClick={() => loadExam(resultingExam.id)}
						className={clsx(
							"bg-white border border-ielts-writing text-ielts-writing w-full max-w-[200px] rounded-xl h-[70px] self-end",
							"hover:bg-ielts-writing hover:text-white disabled:bg-ielts-writing/40 disabled:cursor-not-allowed",
							"transition ease-in-out duration-300",
						)}>
						Perform Exam
					</button>
				)}
				<button
					disabled={(!task1 && !task2) || isLoading}
					data-tip="Please generate all three passages"
					onClick={submitExam}
					className={clsx(
						"bg-ielts-writing/70 border border-ielts-writing text-white w-full max-w-[200px] rounded-xl h-[70px] self-end",
						"hover:bg-ielts-writing disabled:bg-ielts-writing/40 disabled:cursor-not-allowed",
						"transition ease-in-out duration-300",
						!task1 && !task2 && "tooltip",
					)}>
					{isLoading ? (
						<div className="flex items-center justify-center">
							<BsArrowRepeat className="text-white animate-spin" size={25} />
						</div>
					) : (
						"Submit"
					)}
				</button>
			</div>
		</>
	);
};

export default WritingGeneration;
