/* eslint-disable @next/next/no-img-element */

import Head from "next/head";
import Navbar from "@/components/Navbar";
import {ToastContainer} from "react-toastify";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import useUser from "@/hooks/useUser";
import Sidebar from "@/components/Sidebar";
import dynamic from "next/dynamic";
import {BsCheckCircleFill, BsMicFill, BsPauseCircle, BsPauseFill, BsPlayCircle, BsPlayFill, BsTrashFill} from "react-icons/bs";
import {useEffect, useState} from "react";
import Layout from "@/components/High/Layout";

const Waveform = dynamic(() => import("../components/Waveform"), {ssr: false});
const ReactMediaRecorder = dynamic(() => import("react-media-recorder").then((mod) => mod.ReactMediaRecorder), {
	ssr: false,
});

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() {
	const {user} = useUser({redirectTo: "/login"});
	const [recordingDuration, setRecordingDuration] = useState(0);
	const [isRecording, setIsRecording] = useState(false);
	const [mediaBlob, setMediaBlob] = useState<string>();

	useEffect(() => {
		let recordingInterval: NodeJS.Timer | undefined = undefined;
		if (isRecording) {
			recordingInterval = setInterval(() => setRecordingDuration((prev) => prev + 1), 1000);
		} else if (recordingInterval) {
			clearInterval(recordingInterval);
		}

		return () => {
			if (recordingInterval) clearInterval(recordingInterval);
		};
	}, [isRecording]);

	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 />
			{user && (
				<Layout user={user}>
					<ReactMediaRecorder
						audio
						onStop={(blob) => setMediaBlob(blob)}
						render={({status, startRecording, stopRecording, pauseRecording, resumeRecording, clearBlobUrl, mediaBlobUrl}) => (
							<div className="w-full p-4 px-8 bg-transparent border-2 border-mti-gray-platinum rounded-2xl flex-col gap-8 items-center">
								<p className="text-base font-normal">Record your answer:</p>
								<div className="flex gap-8 items-center justify-center py-8">
									{status === "idle" && (
										<>
											<div className="w-full h-2 max-w-4xl bg-mti-gray-smoke rounded-full" />
											{status === "idle" && (
												<BsMicFill
													onClick={() => {
														setRecordingDuration(0);
														startRecording();
														setIsRecording(true);
													}}
													className="h-5 w-5 text-mti-gray-cool cursor-pointer"
												/>
											)}
										</>
									)}
									{status === "recording" && (
										<>
											<div className="flex gap-4 items-center">
												<span className="text-xs w-9">
													{Math.round(recordingDuration / 60)
														.toString(10)
														.padStart(2, "0")}
													:
													{Math.round(recordingDuration % 60)
														.toString(10)
														.padStart(2, "0")}
												</span>
											</div>
											<div className="w-full h-2 max-w-4xl bg-mti-gray-smoke rounded-full" />
											<div className="flex gap-4 items-center">
												<BsPauseCircle
													onClick={() => {
														setIsRecording(false);
														pauseRecording();
													}}
													className="text-red-500 w-8 h-8 cursor-pointer"
												/>
												<BsCheckCircleFill
													onClick={() => {
														setIsRecording(false);
														stopRecording();
													}}
													className="text-mti-green-light w-8 h-8 cursor-pointer"
												/>
											</div>
										</>
									)}
									{status === "paused" && (
										<>
											<div className="flex gap-4 items-center">
												<span className="text-xs w-9">
													{Math.floor(recordingDuration / 60)
														.toString(10)
														.padStart(2, "0")}
													:
													{Math.floor(recordingDuration % 60)
														.toString(10)
														.padStart(2, "0")}
												</span>
											</div>
											<div className="w-full h-2 max-w-4xl bg-mti-gray-smoke rounded-full" />
											<div className="flex gap-4 items-center">
												<BsPlayCircle
													onClick={() => {
														setIsRecording(true);
														resumeRecording();
													}}
													className="text-mti-green-light w-8 h-8 cursor-pointer"
												/>
												<BsCheckCircleFill
													onClick={() => {
														setIsRecording(false);
														stopRecording();
													}}
													className="text-mti-green-light w-8 h-8 cursor-pointer"
												/>
											</div>
										</>
									)}
									{status === "stopped" && mediaBlobUrl && (
										<>
											<Waveform audio={mediaBlobUrl} waveColor="#FCDDEC" progressColor="#EF5DA8" />
											<div className="flex gap-4 items-center">
												<BsTrashFill
													className="text-mti-gray-cool cursor-pointer w-5 h-5"
													onClick={() => {
														setRecordingDuration(0);
														clearBlobUrl();
													}}
												/>

												<BsMicFill
													onClick={() => {
														clearBlobUrl();
														setRecordingDuration(0);
														startRecording();
														setIsRecording(true);
													}}
													className="h-5 w-5 text-mti-gray-cool cursor-pointer"
												/>
											</div>
										</>
									)}
								</div>
							</div>
						)}
					/>
				</Layout>
			)}
		</>
	);
}
