import Checkbox from "@/components/Low/Checkbox";
import Input from "@/components/Low/Input";
import Select from "@/components/Low/Select";
import {Difficulty, Exercise, InteractiveSpeakingExercise, SpeakingExam, SpeakingExercise} from "@/interfaces/exam";
import {AVATARS} from "@/resources/speakingAvatars";
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 {capitalize, sample, uniq} from "lodash";
import moment from "moment";
import {useRouter} from "next/router";
import {generate} from "random-words";
import {useEffect, useState, Dispatch, SetStateAction} 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 PartTab = ({
	part,
	index,
	difficulty,
	setPart,
	updatePart,
}: {
	part?: SpeakingPart;
	difficulty: Difficulty;
	index: number;
	setPart: (part?: SpeakingPart) => void;
	updatePart: Dispatch<SetStateAction<SpeakingPart | undefined>>;
}) => {
	const [gender, setGender] = useState<"male" | "female">("male");
	const [isLoading, setIsLoading] = useState(false);

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

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

		axios
			.get(`/api/exam/speaking/generate/speaking_task_${index}?${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.");
				console.log(result.data);
				setPart(result.data);
			})
			.catch((error) => {
				console.log(error);
				toast.error("Something went wrong!");
			})
			.finally(() => setIsLoading(false));
	};

	const generateVideo = async () => {
		if (!part) return toast.error("Please generate the first part before generating the video!");
		toast.info("This will take quite a while, please do not leave this page or close the tab/window.");

		const avatar = sample(AVATARS.filter((x) => x.gender === gender));

		setIsLoading(true);
		const initialTime = moment();

		axios
			.post(`/api/exam/speaking/generate/speaking/generate_video_${index}`, {
				...part,
				avatar: avatar?.id,
			})
			.then((result) => {
				const isError = typeof result.data === "string" || moment().diff(initialTime, "seconds") < 60;

				playSound(isError ? "error" : "check");
				console.log(result.data);
				if (isError) return toast.error("Something went wrong, please try to generate the video again.");
				setPart({
					...part,
					result: {...result.data, topic: part?.topic},
					gender,
					avatar,
				});
			})
			.catch((e) => {
				toast.error("Something went wrong!");
				console.log(e);
			})
			.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 flex-col gap-3 w-full">
				<label className="font-normal text-base text-mti-gray-dim">Gender</label>
				<Select
					options={[
						{value: "male", label: "Male"},
						{value: "female", label: "Female"},
					]}
					value={{value: gender, label: capitalize(gender)}}
					onChange={(value) => (value ? setGender(value.value as typeof gender) : null)}
					disabled={isLoading}
				/>
			</div>
			<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>
				<button
					onClick={generateVideo}
					disabled={isLoading || !part}
					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 Video"
					)}
				</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 && !isLoading && (
				<div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide h-96">
					<h3 className="text-xl font-semibold">
						{!!part.first_topic && !!part.second_topic ? `${part.first_topic} & ${part.second_topic}` : 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>
					)}
					{part.result && <span className="font-bold mt-4">Video Generated: ✅</span>}
					{part.avatar && part.gender && (
						<span>
							<b>Instructor:</b> {part.avatar.name} - {capitalize(part.avatar.gender)}
						</span>
					)}
					{part.questions?.map((question, index) => (
						<Input
							key={index}
							type="text"
							label="Question"
							name="question"
							required
							value={question}
							onChange={(value) =>
								updatePart((part?: SpeakingPart) => {
									if (part) {
										return {
											...part,
											questions: part.questions?.map((x, xIndex) => (xIndex === index ? value : x)),
										} as SpeakingPart;
									}

									return part;
								})
							}
						/>
					))}
				</div>
			)}
		</Tab.Panel>
	);
};

interface SpeakingPart {
	prompts?: string[];
	question?: string;
	questions?: string[];
	topic: string;
	first_topic?: string;
	second_topic?: string;
	result?: SpeakingExercise | InteractiveSpeakingExercise;
	gender?: "male" | "female";
	avatar?: (typeof AVATARS)[number];
}

interface Props {
	id: string;
}

const SpeakingGeneration = ({id}: Props) => {
	const [part1, setPart1] = useState<SpeakingPart>();
	const [part2, setPart2] = useState<SpeakingPart>();
	const [part3, setPart3] = useState<SpeakingPart>();
	const [minTimer, setMinTimer] = useState(14);
	const [isLoading, setIsLoading] = useState(false);
	const [resultingExam, setResultingExam] = useState<SpeakingExam>();
	const [difficulty, setDifficulty] = useState<Difficulty>(sample(DIFFICULTIES)!);
	const [isPrivate, setPrivate] = useState<boolean>(false);

	useEffect(() => {
		const parts = [part1, part2, part3].filter((x) => !!x);
		setMinTimer(parts.length === 0 ? 5 : parts.length * 5);
	}, [part1, part2, part3]);

	const router = useRouter();

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

	const submitExam = () => {
		if (!part1?.result && !part2?.result && !part3?.result) return toast.error("Please generate at least one task!");

		if (!id) {
			toast.error("Please insert a title before submitting");
			return;
		}

		setIsLoading(true);

		const genders = [part1?.gender, part2?.gender, part3?.gender].filter((x) => !!x);

		const exercises = [part1?.result, part2?.result, part3?.result]
			.filter((x) => !!x)
			.map((x) => ({
				...x,
				first_title: x?.type === "interactiveSpeaking" ? x.first_topic : undefined,
				second_title: x?.type === "interactiveSpeaking" ? x.second_topic : undefined,
			}));

		const exam: SpeakingExam = {
			id,
			isDiagnostic: false,
			exercises: exercises as (SpeakingExercise | InteractiveSpeakingExercise)[],
			minTimer,
			variant: minTimer >= 14 ? "full" : "partial",
			module: "speaking",
			instructorGender: genders.every((x) => x === "male") ? "male" : genders.every((x) => x === "female") ? "female" : "varied",
			private: isPrivate,
		};

		axios
			.post(`/api/exam/speaking`, exam)
			.then((result) => {
				playSound("sent");
				console.log(`Generated Exam ID: ${result.data.id}`);
				toast.success(`Generated Exam ID: ${result.data.id}`);
				setResultingExam(result.data);

				setPart1(undefined);
				setPart2(undefined);
				setPart3(undefined);
				setDifficulty(sample(DIFFICULTIES)!);
				setMinTimer(14);
			})
			.catch((error) => {
				console.log(error);
				toast.error("Something went wrong while generating, please try again later.");
			})
			.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 (
		<>
			<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) < 5 ? 5 : 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={!!part1 || !!part2 || !!part3}
					/>
				</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-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 flex gap-2 items-center justify-center",
								"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",
							)
						}>
						Exercise 1 {part1 && part1.result && <BsCheck />}
					</Tab>
					<Tab
						className={({selected}) =>
							clsx(
								"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/70 flex gap-2 items-center justify-center",
								"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",
							)
						}>
						Exercise 2 {part2 && part2.result && <BsCheck />}
					</Tab>
					<Tab
						className={({selected}) =>
							clsx(
								"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/70 flex gap-2 items-center justify-center",
								"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",
							)
						}>
						Interactive {part3 && part3.result && <BsCheck />}
					</Tab>
				</Tab.List>
				<Tab.Panels>
					{[
						{part: part1, setPart: setPart1},
						{part: part2, setPart: setPart2},
						{part: part3, setPart: setPart3},
					].map(({part, setPart}, index) => (
						<PartTab difficulty={difficulty} part={part} index={index + 1} key={index} setPart={setPart} updatePart={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?.result && !part2?.result && !part3?.result) || 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;
