import Checkbox from "@/components/Low/Checkbox";
import Input from "@/components/Low/Input";
import Select from "@/components/Low/Select";
import {Difficulty, 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 {capitalize, sample} from "lodash";
import {useRouter} from "next/router";
import {generate} from "random-words";
import {useEffect, useState} from "react";
import {BsArrowRepeat, BsCheck} from "react-icons/bs";
import {toast} from "react-toastify";
import {v4} from "uuid";

const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"];

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

	const generate = () => {
		setIsLoading(true);

		const url = new URLSearchParams();
		url.append("difficulty", difficulty);

		axios
			.get(`/api/exam/writing/generate/writing_task${index}_general?${url.toString()}`)
			.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>
	);
};

interface Props {
	id: string;
}

const WritingGeneration = ({id}: Props) => {
	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>();
	const [difficulty, setDifficulty] = useState<Difficulty>(sample(DIFFICULTIES)!);
	const [isPrivate, setPrivate] = useState<boolean>(false);

	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;
		}

		if (!id) {
			toast.error("Please insert a title 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,
			variant: exercise1 && exercise2 ? "full" : "partial",
			difficulty,
			private: isPrivate,
		};

		axios
			.post(`/api/exam/writing`, exam)
			.then((result) => {
				console.log(`Generated Exam ID: ${result.data.id}`);
				toast.success(`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);
				setDifficulty(sample(DIFFICULTIES)!);
			})
			.catch((error) => {
				console.log(error);
				toast.error("Something went wrong while generating, please try again later.");
			})
			.finally(() => setIsLoading(false));
	};

	return (
		<>
			<div className="flex gap-4 w-full items-center">
				<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>
				<div className="flex flex-col gap-3 w-1/2">
					<label className="font-normal text-base text-mti-gray-dim">Difficulty</label>
					<Select
						options={DIFFICULTIES.map((x) => ({value: x, label: capitalize(x)}))}
						onChange={(value) => (value ? setDifficulty(value.value as Difficulty) : null)}
						value={{value: difficulty, label: capitalize(difficulty)}}
						disabled={!!task1 || !!task2}
					/>
				</div>

				<div className="flex flex-col gap-3 w-fit h-fit">
					<div className="h-6" />
					<Checkbox isChecked={isPrivate} onChange={setPrivate}>
						Privacy (Only available for Assignments)
					</Checkbox>
				</div>
			</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 difficulty={difficulty} 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;
