import {Module} from "@/interfaces";
import useExamStore from "@/stores/examStore";
import {moduleLabels} from "@/utils/moduleUtils";
import {ReactNode, useEffect, useState} from "react";
import {BsBook, BsHeadphones, BsMegaphone, BsPen, BsStopwatch} from "react-icons/bs";
import ProgressBar from "../Low/ProgressBar";

interface Props {
	minTimer: number;
	module: Module;
	label?: string;
	exerciseIndex: number;
	totalExercises: number;
	disableTimer?: boolean;
}

export default function ModuleTitle({minTimer, module, label, exerciseIndex, totalExercises, disableTimer = false}: Props) {
	const [timer, setTimer] = useState(minTimer * 60);
	const setHasExamEnded = useExamStore((state) => state.setHasExamEnded);

	useEffect(() => {
		if (!disableTimer) {
			const timerInterval = setInterval(() => setTimer((prev) => prev - 1), 1000);

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

	useEffect(() => {
		if (timer <= 0) setHasExamEnded(true);
	}, [setHasExamEnded, timer]);

	const moduleIcon: {[key in Module]: ReactNode} = {
		reading: <BsBook className="text-ielts-reading w-6 h-6" />,
		listening: <BsHeadphones className="text-ielts-listening w-6 h-6" />,
		writing: <BsPen className="text-ielts-writing w-6 h-6" />,
		speaking: <BsMegaphone className="text-ielts-speaking w-6 h-6" />,
	};

	return (
		<>
			<div className="absolute top-4 right-6 bg-mti-gray-seasalt px-3 py-2 flex items-center gap-2 rounded-full text-mti-gray-davy">
				<BsStopwatch className="w-4 h-4" />
				<span className="text-sm font-semibold w-11">
					{timer > 0 && (
						<>
							{Math.floor(timer / 60)
								.toString(10)
								.padStart(2, "0")}
							:
							{Math.floor(timer % 60)
								.toString(10)
								.padStart(2, "0")}
						</>
					)}
					{timer <= 0 && <>00:00</>}
				</span>
			</div>
			<div className="flex gap-6 w-full h-fit items-center mt-5">
				<div className="w-12 h-12 bg-mti-gray-smoke flex items-center justify-center rounded-lg">{moduleIcon[module]}</div>
				<div className="flex flex-col gap-3 w-full">
					<div className="w-full flex justify-between">
						<span className="text-base font-semibold">
							{moduleLabels[module]} exam {label && `- ${label}`}
						</span>
						<span className="text-xs font-normal self-end text-mti-gray-davy">
							Question {exerciseIndex}/{totalExercises}
						</span>
					</div>
					<ProgressBar color={module} label="" percentage={(exerciseIndex * 100) / totalExercises} className="h-2 w-full" />
				</div>
			</div>
		</>
	);
}
