import Input from "@/components/Low/Input";
import {Exercise, SpeakingExam} from "@/interfaces/exam";
import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams";
import {playSound} from "@/utils/sound";
import {convertCamelCaseToReadable} from "@/utils/string";
import {Tab} from "@headlessui/react";
import axios from "axios";
import clsx from "clsx";
import {useRouter} from "next/router";
import {useState} from "react";
import {BsArrowRepeat} from "react-icons/bs";
import {toast} from "react-toastify";

const PartTab = ({part, index, setPart}: {part?: SpeakingPart; index: number; setPart: (part?: SpeakingPart) => void}) => {
	const [isLoading, setIsLoading] = useState(false);

	const generate = () => {
		setPart(undefined);
		setIsLoading(true);
		axios
			.get(`/api/exam/speaking/generate/speaking_task_${index}`)
			.then((result) => {
				playSound("check");
				setPart(result.data);
			})
			.catch((error) => {
				console.log(error);
				toast.error("Something went wrong!");
			})
			.finally(() => setIsLoading(false));
	};

	return (
		<Tab.Panel className="w-full bg-ielts-speaking/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}
					data-tip="The passage is currently being generated"
					className={clsx(
						"bg-ielts-speaking/70 border border-ielts-speaking text-white w-full rounded-xl h-[70px]",
						"hover:bg-ielts-speaking disabled:bg-ielts-speaking/40 disabled:cursor-not-allowed",
						"transition ease-in-out duration-300",
						isLoading && "tooltip",
					)}>
					{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-speaking")} />
					<span className={clsx("font-bold text-2xl text-ielts-speaking")}>Generating...</span>
				</div>
			)}
			{part && (
				<div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide h-96">
					<h3 className="text-xl font-semibold">{part.topic}</h3>
					{part.question && <span className="w-full">{part.question}</span>}
					{part.questions && (
						<div className="flex flex-col gap-1">
							{part.questions.map((question, index) => (
								<span className="w-full" key={index}>
									- {question}
								</span>
							))}
						</div>
					)}
					{part.prompts && (
						<div className="flex flex-col gap-1">
							<span className="font-medium">You should talk about the following things:</span>
							{part.prompts.map((prompt, index) => (
								<span className="w-full" key={index}>
									- {prompt}
								</span>
							))}
						</div>
					)}
				</div>
			)}
		</Tab.Panel>
	);
};

interface SpeakingPart {
	prompts?: string[];
	question?: string;
	questions?: string[];
	topic: string;
}

const SpeakingGeneration = () => {
	const [part1, setPart1] = useState<SpeakingPart>();
	const [part2, setPart2] = useState<SpeakingPart>();
	const [part3, setPart3] = useState<SpeakingPart>();
	const [isLoading, setIsLoading] = useState(false);
	const [resultingExam, setResultingExam] = useState<SpeakingExam>();

	const router = useRouter();

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

	const submitExam = () => {
		if (!part1 || !part2 || !part3) return toast.error("Please generate all for tasks!");

		setIsLoading(true);

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

				setPart1(undefined);
				setPart2(undefined);
				setPart3(undefined);
			})
			.catch((error) => {
				console.log(error);
				toast.error("Something went wrong!");
			})
			.finally(() => setIsLoading(false));
	};

	const loadExam = async (examId: string) => {
		const exam = await getExamById("speaking", 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(["speaking"]);

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

	return (
		<>
			<Tab.Group>
				<Tab.List className="flex space-x-1 rounded-xl bg-ielts-speaking/20 p-1">
					<Tab
						className={({selected}) =>
							clsx(
								"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/70",
								"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking 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-speaking",
							)
						}>
						Task 1
					</Tab>
					<Tab
						className={({selected}) =>
							clsx(
								"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/70",
								"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking 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-speaking",
							)
						}>
						Task 2
					</Tab>
					<Tab
						className={({selected}) =>
							clsx(
								"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/70",
								"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking 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-speaking",
							)
						}>
						Task 3
					</Tab>
				</Tab.List>
				<Tab.Panels>
					{[
						{part: part1, setPart: setPart1},
						{part: part2, setPart: setPart2},
						{part: part3, setPart: setPart3},
					].map(({part, setPart}, index) => (
						<PartTab part={part} index={index + 1} key={index} setPart={setPart} />
					))}
				</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-speaking text-ielts-speaking w-full max-w-[200px] rounded-xl h-[70px] self-end",
							"hover:bg-ielts-speaking hover:text-white disabled:bg-ielts-speaking/40 disabled:cursor-not-allowed",
							"transition ease-in-out duration-300",
						)}>
						Perform Exam
					</button>
				)}
				<button
					disabled={!part1 || !part2 || !part3 || isLoading}
					data-tip="Please generate all three passages"
					onClick={submitExam}
					className={clsx(
						"bg-ielts-speaking/70 border border-ielts-speaking text-white w-full max-w-[200px] rounded-xl h-[70px] self-end",
						"hover:bg-ielts-speaking disabled:bg-ielts-speaking/40 disabled:cursor-not-allowed",
						"transition ease-in-out duration-300",
						(!part1 || !part2 || !part3) && "tooltip",
					)}>
					{isLoading ? (
						<div className="flex items-center justify-center">
							<BsArrowRepeat className="text-white animate-spin" size={25} />
						</div>
					) : (
						"Submit"
					)}
				</button>
			</div>
		</>
	);
};

export default SpeakingGeneration;
