/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import Navbar from "@/components/Navbar";
import {BsFileEarmarkText, BsPencil, BsStar, BsBook, BsHeadphones, BsPen, BsMegaphone} from "react-icons/bs";
import {ArcElement, LinearScale, Chart as ChartJS, CategoryScale, PointElement, LineElement, Legend, Tooltip} from "chart.js";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {useEffect, useState} from "react";
import useStats from "@/hooks/useStats";
import {
	averageScore,
	totalExams,
	totalExamsByModule,
	groupBySession,
	groupByModule,
	formatModuleAverageScoreStats,
	calculateModuleAverageScoreStats,
} from "@/utils/stats";
import useUser from "@/hooks/useUser";
import Sidebar from "@/components/Sidebar";
import Diagnostic from "@/components/Diagnostic";
import {ToastContainer} from "react-toastify";
import {capitalize} from "lodash";
import {Module} from "@/interfaces";
import ProgressBar from "@/components/Low/ProgressBar";
import Layout from "@/components/High/Layout";
import {calculateAverageLevel, calculateBandScore} from "@/utils/score";
import {MODULE_ARRAY} from "@/utils/moduleUtils";
import {Chart} from "react-chartjs-2";

ChartJS.register(LinearScale, CategoryScale, PointElement, LineElement, Legend, Tooltip);

const COLORS = ["#1EB3FF", "#FF790A", "#3D9F11", "#EF5DA8"];

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

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

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

export default function Stats() {
	const {user} = useUser({redirectTo: "/login"});
	const {stats} = useStats(user?.id);

	const totalExamsData = {
		labels: MODULE_ARRAY.map((x) => capitalize(x)),
		datasets: [
			{
				label: "Total exams",
				data: MODULE_ARRAY.map((x) => totalExamsByModule(stats, x)),
				backgroundColor: ["#1EB3FF", "#FF790A", "#3D9F11", "#EF5DA8"],
			},
		],
	};

	const calculateTotalScorePerSession = () => {
		const groupedBySession = groupBySession(stats);
		const sessionAverage = Object.keys(groupedBySession).map((x: string) => {
			const session = groupedBySession[x];
			const moduleStats = groupByModule(session);
			const moduleScores = Object.keys(moduleStats).map((y) => {
				const correct = moduleStats[y].reduce((accumulator, current) => accumulator + current.score.correct, 0);
				const total = moduleStats[y].reduce((accumulator, current) => accumulator + current.score.total, 0);

				return {
					module: y,
					score: calculateBandScore(correct, total, y as Module, user?.focus || "academic"),
				};
			});

			return moduleScores.reduce((acc, curr) => acc + curr.score, 0) / 4;
		});

		return sessionAverage;
	};

	const calculateModularScorePerSession = (module: Module) => {
		const groupedBySession = groupBySession(stats);
		const sessionAverage = Object.keys(groupedBySession).map((x: string) => {
			const session = groupedBySession[x];
			const moduleStats = groupByModule(session);
			if (!Object.keys(moduleStats).includes(module)) return null;
			const correct = moduleStats[module].reduce((acc, curr) => acc + curr.score.correct, 0);
			const total = moduleStats[module].reduce((acc, curr) => acc + curr.score.total, 0);

			return calculateBandScore(correct, total, module, user?.focus || "academic");
		});

		return sessionAverage;
	};

	return (
		<>
			<Head>
				<title>Stats | EnCoach</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}>
					<section className="w-full flex gap-8">
						<img src={user.profilePicture} alt={user.name} className="aspect-square h-64 rounded-3xl drop-shadow-xl object-cover" />
						<div className="flex flex-col gap-4 py-4 w-full">
							<div className="flex justify-between w-full gap-8">
								<div className="flex flex-col gap-2 py-2">
									<h1 className="font-bold text-4xl">{user.name}</h1>
									<h6 className="font-normal text-base text-mti-gray-taupe">{capitalize(user.type)}</h6>
								</div>
								<ProgressBar
									label={`Level ${calculateAverageLevel(user.levels).toFixed(1)}`}
									percentage={100}
									color="purple"
									className="max-w-xs w-32 self-end h-10"
								/>
							</div>
							<ProgressBar
								label=""
								percentage={Math.round((calculateAverageLevel(user.levels) * 100) / calculateAverageLevel(user.desiredLevels))}
								color="red"
								className="w-full h-3 drop-shadow-lg"
							/>
							<div className="flex justify-between w-full mt-8">
								<div className="flex gap-4 items-center">
									<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
										<BsFileEarmarkText className="w-8 h-8 text-mti-red-light" />
									</div>
									<div className="flex flex-col">
										<span className="font-bold text-xl">{Object.keys(groupBySession(stats)).length}</span>
										<span className="font-normal text-base text-mti-gray-dim">Exams</span>
									</div>
								</div>
								<div className="flex gap-4 items-center">
									<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
										<BsPencil className="w-8 h-8 text-mti-red-light" />
									</div>
									<div className="flex flex-col">
										<span className="font-bold text-xl">{stats.length}</span>
										<span className="font-normal text-base text-mti-gray-dim">Exercises</span>
									</div>
								</div>
								<div className="flex gap-4 items-center">
									<div className="w-16 h-16 border border-mti-gray-platinum bg-mti-gray-smoke flex items-center justify-center rounded-xl">
										<BsStar className="w-8 h-8 text-mti-red-light" />
									</div>
									<div className="flex flex-col">
										<span className="font-bold text-xl">{averageScore(stats)}%</span>
										<span className="font-normal text-base text-mti-gray-dim">Average Score</span>
									</div>
								</div>
							</div>
						</div>
					</section>
					{stats.length > 0 && (
						<section className="flex flex-col gap-3">
							<div className="flex gap-4 flex-wrap">
								{/* Exams per module */}
								<div className="flex flex-col gap-12 border w-full h-fit max-w-xs border-mti-gray-platinum p-4 pb-12 rounded-xl">
									<span className="text-sm font-bold">Exams per Module</span>
									<div className="flex flex-col gap-4">
										<div className="flex flex-col gap-2">
											<div className="flex justify-between items-end">
												<span className="text-xs">
													<span className="font-medium">{totalExamsByModule(stats, "reading")}</span> of{" "}
													<span className="font-medium">{Object.keys(groupBySession(stats)).length}</span>
												</span>
												<span className="text-xs">Reading</span>
											</div>
											<ProgressBar
												color="reading"
												percentage={(totalExamsByModule(stats, "reading") * 100) / Object.keys(groupBySession(stats)).length}
												label=""
												className="h-1"
											/>
										</div>
										<div className="flex flex-col gap-2">
											<div className="flex justify-between items-end">
												<span className="text-xs">
													<span className="font-medium">{totalExamsByModule(stats, "listening")}</span> of{" "}
													<span className="font-medium">{Object.keys(groupBySession(stats)).length}</span>
												</span>
												<span className="text-xs">Listening</span>
											</div>
											<ProgressBar
												color="listening"
												percentage={
													(totalExamsByModule(stats, "listening") * 100) / Object.keys(groupBySession(stats)).length
												}
												label=""
												className="h-1"
											/>
										</div>
										<div className="flex flex-col gap-2">
											<div className="flex justify-between items-end">
												<span className="text-xs">
													<span className="font-medium">{totalExamsByModule(stats, "writing")}</span> of{" "}
													<span className="font-medium">{Object.keys(groupBySession(stats)).length}</span>
												</span>
												<span className="text-xs">Writing</span>
											</div>
											<ProgressBar
												color="writing"
												percentage={(totalExamsByModule(stats, "writing") * 100) / Object.keys(groupBySession(stats)).length}
												label=""
												className="h-1"
											/>
										</div>
										<div className="flex flex-col gap-2">
											<div className="flex justify-between items-end">
												<span className="text-xs">
													<span className="font-medium">{totalExamsByModule(stats, "speaking")}</span> of{" "}
													<span className="font-medium">{Object.keys(groupBySession(stats)).length}</span>
												</span>
												<span className="text-xs">Speaking</span>
											</div>
											<ProgressBar
												color="speaking"
												percentage={(totalExamsByModule(stats, "speaking") * 100) / Object.keys(groupBySession(stats)).length}
												label=""
												className="h-1"
											/>
										</div>
									</div>
								</div>

								<div className="w-full max-w-3xl border border-mti-gray-platinum p-4 pb-12 rounded-xl">
									<span className="text-sm font-bold">Total Score Band per Session</span>
									<Chart
										type="line"
										data={{
											labels: Object.keys(groupBySession(stats)).map((_, index) => index),
											datasets: [
												{
													type: "line",
													label: "Total",
													fill: false,
													borderColor: "#6A5FB1",
													backgroundColor: "#7872BF",
													borderWidth: 2,
													spanGaps: true,
													data: calculateTotalScorePerSession(),
												},
											],
										}}
									/>
								</div>

								<div className="w-full max-w-3xl border border-mti-gray-platinum p-4 pb-12 rounded-xl">
									<span className="text-sm font-bold">Module Score Band per Session</span>
									<Chart
										type="line"
										data={{
											labels: Object.keys(groupBySession(stats)).map((_, index) => index),
											datasets: [
												...MODULE_ARRAY.map((module, index) => ({
													type: "line" as const,
													label: capitalize(module),
													borderColor: COLORS[index],
													backgroundColor: COLORS[index],
													borderWidth: 2,
													data: calculateModularScorePerSession(module),
												})),
											],
										}}
									/>
								</div>
							</div>
						</section>
					)}
					{stats.length === 0 && (
						<section className="flex flex-col gap-3">
							<span className="font-semibold ml-1">No stats to display...</span>
						</section>
					)}
				</Layout>
			)}
		</>
	);
}
