import {infoButtonStyle} from "@/constants/buttonStyles";
import {Module} from "@/interfaces";
import {User} from "@/interfaces/user";
import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams";
import axios from "axios";
import clsx from "clsx";
import {useRouter} from "next/router";
import {useEffect, useState} from "react";
import {ToastContainer, toast} from "react-toastify";

interface Props {
	user: User;
}

const DIAGNOSTIC_EXAMS = [
	["reading", ""],
	["listening", ""],
	["writing", ""],
	["speaking", ""],
];

export default function Diagnostic({user}: Props) {
	const [focus, setFocus] = useState<"academic" | "general">();
	const [isInsert, setIsInsert] = useState(false);

	const router = useRouter();

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

	const selectExam = () => {
		const examPromises = DIAGNOSTIC_EXAMS.map((exam) => getExamById(exam[0] as Module, exam[1]));

		Promise.all(examPromises).then((exams) => {
			if (exams.every((x) => !!x)) {
				setExams(exams.map((x) => x!));
				setSelectedModules(exams.map((x) => x!.module));
				router.push("/exam");
			}
		});
	};

	const onPerformDiagnosis = async () => {
		axios
			.post("/api/users/update", {focus, isFirstLogin: false})
			.then(selectExam)
			.catch(() => {
				toast.error("Something went wrong, please try again later!", {toastId: "user-update-error"});
			});
	};

	useEffect(() => {
		toast.error("Something went wrong, please try again later!", {toastId: "user-update-error"});
	}, []);

	if (!focus) {
		return (
			<div className="bg-white p-16 rounded-2xl flex flex-col items-center justify-center gap-8 h-96 relative shadow-md">
				<h2 className="absolute top-8 font-semibold text-xl">What is your focus?</h2>
				<div className="flex flex-col gap-4 justify-self-stretch">
					<button onClick={() => setFocus("academic")} className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}>
						Academic
					</button>
					<button onClick={() => setFocus("general")} className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}>
						General
					</button>
				</div>
			</div>
		);
	}

	return (
		<div className="bg-white p-16 rounded-2xl flex flex-col items-center justify-center gap-8 h-96 relative shadow-md">
			<h2 className="absolute top-8 font-semibold text-xl">What is your current IELTS level?</h2>
			<div className="flex flex-col gap-4">
				<button onClick={() => setIsInsert(true)} className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}>
					Insert my IELTS level
				</button>
				<button onClick={onPerformDiagnosis} className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}>
					Perform a Diagnosis Test
				</button>
			</div>
		</div>
	);
}
