import Input from "@/components/Low/Input";
import Select from "@/components/Low/Select";
import {Difficulty, Exercise, ReadingExam, ReadingPart} from "@/interfaces/exam";
import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams";
import {playSound} from "@/utils/sound";
import {convertCamelCaseToReadable} from "@/utils/string";
import {generate} from "random-words";
import {Tab} from "@headlessui/react";
import axios from "axios";
import clsx from "clsx";
import {capitalize, sample} from "lodash";
import {useRouter} from "next/router";
import {useEffect, useState, Dispatch, SetStateAction} from "react";
import {BsArrowRepeat, BsCheck} from "react-icons/bs";
import {toast} from "react-toastify";
import {v4} from "uuid";
import FillBlanksEdit from "@/components/Generation/fill.blanks.edit";
import TrueFalseEdit from "@/components/Generation/true.false.edit";
import WriteBlanksEdit from "@/components/Generation/write.blanks.edit";
import MatchSentencesEdit from "@/components/Generation/match.sentences.edit";
import MultipleChoiceEdit from "@/components/Generation/multiple.choice.edit";
import Checkbox from "@/components/Low/Checkbox";

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

const availableTypes = [
	{type: "fillBlanks", label: "Fill the Blanks"},
	{type: "trueFalse", label: "True or False"},
	{type: "writeBlanks", label: "Write the Blanks"},
	{type: "paragraphMatch", label: "Match Sentences"},
];

const PartTab = ({
	part,
	difficulty,
	index,
	setPart,
	updatePart,
}: {
	part?: ReadingPart;
	index: number;
	difficulty: Difficulty;
	setPart: (part?: ReadingPart) => void;
	updatePart: Dispatch<SetStateAction<ReadingPart | undefined>>;
}) => {
	const [topic, setTopic] = useState("");
	const [isLoading, setIsLoading] = useState(false);
	const [types, setTypes] = useState<string[]>([]);

	const toggleType = (type: string) => setTypes((prev) => (prev.includes(type) ? [...prev.filter((x) => x !== type)] : [...prev, type]));

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

		if (topic) url.append("topic", topic);
		if (types) types.forEach((t) => url.append("exercises", t));

		setPart(undefined);
		setIsLoading(true);
		axios
			.get(`/api/exam/reading/generate/reading_passage_${index}${topic || types ? `?${url.toString()}` : ""}`)
			.then((result) => {
				console.log(result.data);

				playSound(typeof result.data === "string" ? "error" : "check");
				if (typeof result.data === "string") return toast.error("Something went wrong, please try to generate again.");
				setPart(result.data);
			})
			.catch((error) => {
				console.log(error);
				toast.error("Something went wrong!");
			})
			.finally(() => setIsLoading(false));
	};

	const renderExercises = () => {
		return part?.exercises.map((exercise) => {
			switch (exercise.type) {
				case "fillBlanks":
					return (
						<>
							<h1>Exercise: Fill Blanks</h1>
							<FillBlanksEdit
								exercise={exercise}
								key={exercise.id}
								updateExercise={(data: any) =>
									updatePart((part?: ReadingPart) => {
										if (part) {
											const exercises = part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)) as Exercise[];
											const updatedPart = {...part, exercises} as ReadingPart;
											return updatedPart;
										}

										return part;
									})
								}
							/>
						</>
					);
				case "trueFalse":
					return (
						<>
							<h1>Exercise: True or False</h1>
							<TrueFalseEdit
								exercise={exercise}
								key={exercise.id}
								updateExercise={(data: any) => {
									updatePart((part?: ReadingPart) => {
										if (part) {
											return {
												...part,
												exercises: part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)),
											} as ReadingPart;
										}

										return part;
									});
								}}
							/>
						</>
					);
				case "multipleChoice":
					return (
						<>
							<h1>Exercise: True or False</h1>
							<MultipleChoiceEdit
								exercise={exercise}
								key={exercise.id}
								updateExercise={(data: any) => {
									updatePart((part?: ReadingPart) => {
										if (part) {
											return {
												...part,
												exercises: part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)),
											} as ReadingPart;
										}

										return part;
									});
								}}
							/>
						</>
					);
				case "writeBlanks":
					return (
						<>
							<h1>Exercise: Write Blanks</h1>
							<WriteBlanksEdit
								exercise={exercise}
								key={exercise.id}
								updateExercise={(data: any) => {
									updatePart((part?: ReadingPart) => {
										if (part) {
											return {
												...part,
												exercises: part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)),
											} as ReadingPart;
										}

										return part;
									});
								}}
							/>
						</>
					);
				case "matchSentences":
					return (
						<>
							<h1>Exercise: Match Sentences</h1>
							<MatchSentencesEdit
								exercise={exercise}
								key={exercise.id}
								updateExercise={(data: any) => {
									updatePart((part?: ReadingPart) => {
										if (part) {
											return {
												...part,
												exercises: part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)),
											} as ReadingPart;
										}

										return part;
									});
								}}
							/>
						</>
					);
				default:
					return null;
			}
		});
	};

	return (
		<Tab.Panel className="w-full bg-ielts-reading/20 min-h-[600px] h-full rounded-xl p-6 flex flex-col gap-4">
			<div className="flex flex-col gap-3">
				<label className="font-normal text-base text-mti-gray-dim">Exercises</label>
				<div className="flex flex-row -2xl:flex-wrap w-full gap-4 -md:justify-center justify-between">
					{[...availableTypes, ...(index === 3 ? [{type: "ideaMatch", label: "Idea Match"}] : [])].map((x) => (
						<span
							onClick={() => toggleType(x.type)}
							key={x.type}
							className={clsx(
								"px-6 py-4 w-64 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
								"transition duration-300 ease-in-out",
								!types.includes(x.type) ? "bg-white border-mti-gray-platinum" : "bg-ielts-reading/70 border-ielts-reading text-white",
							)}>
							{x.label}
						</span>
					))}
				</div>
			</div>
			<div className="flex gap-4 items-end">
				<Input type="text" placeholder="Grand Canyon..." name="topic" label="Topic" onChange={setTopic} roundness="xl" defaultValue={topic} />
				<button
					onClick={generate}
					disabled={isLoading || types.length === 0}
					data-tip="The passage is currently being generated"
					className={clsx(
						"bg-ielts-reading/70 border border-ielts-reading text-white w-full max-w-[200px] rounded-xl h-[70px]",
						"hover:bg-ielts-reading disabled:bg-ielts-reading/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-reading")} />
					<span className={clsx("font-bold text-2xl text-ielts-reading")}>Generating...</span>
				</div>
			)}
			{part && (
				<>
					<div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide">
						<div className="flex gap-4">
							{part.exercises.map((x) => (
								<span className="rounded-xl bg-white border border-ielts-reading p-1 px-4" key={x.id}>
									{x.type && convertCamelCaseToReadable(x.type)}
								</span>
							))}
						</div>
						<h3 className="text-xl font-semibold">{part.text.title}</h3>
						<span className="w-full h-96">{part.text.content}</span>
					</div>
					{renderExercises()}
				</>
			)}
		</Tab.Panel>
	);
};

interface Props {
	id: string;
}

const ReadingGeneration = ({id}: Props) => {
	const [part1, setPart1] = useState<ReadingPart>();
	const [part2, setPart2] = useState<ReadingPart>();
	const [part3, setPart3] = useState<ReadingPart>();
	const [minTimer, setMinTimer] = useState(60);
	const [isLoading, setIsLoading] = useState(false);
	const [resultingExam, setResultingExam] = useState<ReadingExam>();
	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 ? 60 : parts.length * 20);
	}, [part1, part2, part3]);

	const router = useRouter();

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

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

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

	const submitExam = () => {
		const parts = [part1, part2, part3].filter((x) => !!x) as ReadingPart[];
		if (parts.length === 0) {
			toast.error("Please generate at least one passage before submitting");
			return;
		}

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

		setIsLoading(true);
		const exam: ReadingExam = {
			parts,
			isDiagnostic: false,
			minTimer,
			module: "reading",
			id,
			type: "academic",
			variant: parts.length === 3 ? "full" : "partial",
			difficulty,
			private: isPrivate,
		};

		axios
			.post(`/api/exam/reading`, 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(60);
			})
			.catch((error) => {
				console.log(error);
				toast.error(error.response.data.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={!!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-reading/20 p-1">
					<Tab
						className={({selected}) =>
							clsx(
								"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-reading/70 flex gap-2 items-center justify-center",
								"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-reading 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-reading",
							)
						}>
						Passage 1 {part1 && <BsCheck />}
					</Tab>
					<Tab
						className={({selected}) =>
							clsx(
								"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-reading/70 flex gap-2 items-center justify-center",
								"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-reading 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-reading",
							)
						}>
						Passage 2 {part2 && <BsCheck />}
					</Tab>
					<Tab
						className={({selected}) =>
							clsx(
								"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-reading/70 flex gap-2 items-center justify-center",
								"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-reading 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-reading",
							)
						}>
						Passage 3 {part3 && <BsCheck />}
					</Tab>
				</Tab.List>
				<Tab.Panels>
					{[
						{part: part1, setPart: setPart1},
						{part: part2, setPart: setPart2},
						{part: part3, setPart: setPart3},
					].map(({part, setPart}, index) => (
						<PartTab part={part} difficulty={difficulty} 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-reading text-ielts-reading w-full max-w-[200px] rounded-xl h-[70px] self-end",
							"hover:bg-ielts-reading hover:text-white disabled:bg-ielts-reading/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-reading/70 border border-ielts-reading text-white w-full max-w-[200px] rounded-xl h-[70px] self-end",
						"hover:bg-ielts-reading disabled:bg-ielts-reading/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 ReadingGeneration;
