/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import Navbar from "@/components/Navbar";
import {useEffect, useState} from "react";
import {Module} from "@/interfaces";

import Selection from "@/exams/Selection";
import Reading from "@/exams/Reading";
import {Exam, ListeningExam, ReadingExam, SpeakingExam, UserSolution, WritingExam} from "@/interfaces/exam";
import Listening from "@/exams/Listening";
import Writing from "@/exams/Writing";
import {ToastContainer, toast} from "react-toastify";
import Finish from "@/exams/Finish";
import axios from "axios";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {Stat, User} from "@/interfaces/user";
import Speaking from "@/exams/Speaking";

export const getServerSideProps = withIronSessionSsr(({req, res}) => {
	const user = req.session.user;

	if (!user) {
		res.setHeader("location", "/login");
		res.statusCode = 302;
		res.end();
		return {
			props: {
				user: null,
			},
		};
	}

	return {
		props: {user: req.session.user},
	};
}, sessionOptions);

export default function Page({user}: {user: User}) {
	const [userSolutions, setUserSolutions] = useState<UserSolution[]>([]);
	const [selectedModules, setSelectedModules] = useState<Module[]>([]);
	const [hasBeenUploaded, setHasBeenUploaded] = useState(false);
	const [showSolutions, setShowSolutions] = useState(false);
	const [moduleIndex, setModuleIndex] = useState(0);
	const [exam, setExam] = useState<Exam>();
	const [timer, setTimer] = useState(-1);

	useEffect(() => {
		(async () => {
			if (selectedModules.length > 0 && moduleIndex < selectedModules.length) {
				const nextExam = await getExam(selectedModules[moduleIndex]);
				setExam(nextExam ? updateExamWithUserSolutions(nextExam) : undefined);
			}
		})();
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [selectedModules, moduleIndex]);

	useEffect(() => {
		(async () => {
			if (selectedModules.length > 0 && moduleIndex >= selectedModules.length && !hasBeenUploaded) {
				const stats: Stat[] = userSolutions.map((solution) => ({
					...solution,
					exam: solution.exam!,
					module: solution.module!,
					user: user.id,
				}));

				axios
					.post<{ok: boolean}>("/api/stats", stats)
					.then((response) => setHasBeenUploaded(response.data.ok))
					.catch(() => setHasBeenUploaded(false));
			}
		})();
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [selectedModules, moduleIndex, hasBeenUploaded]);

	useEffect(() => {
		if (exam) {
			setTimer(exam.minTimer * 60);
			const timerInterval = setInterval(() => setTimer((prev) => (prev && prev > 0 ? prev - 1 : 0)), 1000);

			return () => {
				clearInterval(timerInterval);
			};
		}
	}, [exam]);

	const getExam = async (module: Module): Promise<Exam | undefined> => {
		const examRequest = await axios<Exam[]>(`/api/exam/${module}`);
		if (examRequest.status !== 200) {
			toast.error("Something went wrong!");
			return undefined;
		}

		const newExam = examRequest.data;

		switch (module) {
			case "reading":
				return newExam.shift() as ReadingExam;
			case "listening":
				return newExam.shift() as ListeningExam;
			case "writing":
				return newExam.shift() as WritingExam;
			case "speaking":
				return newExam.shift() as SpeakingExam;
		}
	};

	const updateExamWithUserSolutions = (exam: Exam): Exam => {
		const exercises = exam.exercises.map((x) => Object.assign(x, {userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions}));

		return Object.assign(exam, exercises);
	};

	const onFinish = (solutions: UserSolution[]) => {
		const solutionIds = solutions.map((x) => x.exercise);

		setUserSolutions((prev) => [...prev.filter((x) => !solutionIds.includes(x.exercise)), ...solutions]);
		setModuleIndex((prev) => prev + 1);
	};

	const renderScreen = () => {
		if (selectedModules.length === 0) {
			return <Selection user={user} onStart={setSelectedModules} />;
		}

		if (moduleIndex >= selectedModules.length) {
			return (
				<Finish
					user={user}
					modules={selectedModules}
					onViewResults={() => {
						setShowSolutions(true);
						setModuleIndex(0);
					}}
					scores={userSolutions.map((x) => ({...x.score, module: x.module}))}
				/>
			);
		}

		if (exam && exam.module === "reading") {
			return <Reading exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
		}

		if (exam && exam.module === "listening") {
			return <Listening exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
		}

		if (exam && exam.module === "writing" && showSolutions) {
			setModuleIndex((prev) => prev + 1);
			return <></>;
		}

		if (exam && exam.module === "writing") {
			return <Writing exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
		}

		if (exam && exam.module === "speaking" && showSolutions) {
			setModuleIndex((prev) => prev + 1);
			return <></>;
		}

		if (exam && exam.module === "speaking") {
			return <Speaking exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
		}

		return <>Loading...</>;
	};

	return (
		<>
			<Head>
				<title>Exam | IELTS GPT</title>
				<meta
					name="description"
					content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
				/>
				<meta name="viewport" content="width=device-width, initial-scale=1" />
				<link rel="icon" href="/favicon.ico" />
			</Head>
			<ToastContainer />
			<main className="w-full h-full min-h-[100vh] flex flex-col items-center bg-neutral-100 text-black pb-4 gap-4">
				<Navbar profilePicture={user.profilePicture} timer={exam ? timer : undefined} />
				{renderScreen()}
			</main>
		</>
	);
}
