import Navbar from "@/components/Navbar";
import SingleDatasetChart from "@/components/UserResultChart";
import useStats from "@/hooks/useStats";
import useUsers from "@/hooks/useUsers";
import {User} from "@/interfaces/user";
import {sessionOptions} from "@/lib/session";
import {formatExerciseAverageScoreStats, formatExerciseTotalStats, formatModuleAverageScoreStats, formatModuleTotalStats} from "@/utils/stats";
import {withIronSessionSsr} from "iron-session/next";
import Head from "next/head";
import {AutoComplete} from "primereact/autocomplete";
import {Divider} from "primereact/divider";
import {useEffect, useState} from "react";
import chartColors from "@/constants/chartColors.json";
import {shuffle} from "lodash";

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 Stats({user}: {user: User}) {
	const [autocompleteValue, setAutocompleteValue] = useState(user.name);
	const [selectedUser, setSelectedUser] = useState<User>();
	const [items, setItems] = useState<User[]>([]);

	const {users, isLoading} = useUsers();
	const {stats, isLoading: isStatsLoading} = useStats(selectedUser?.id);

	const search = (event: {query: string}) => {
		setItems(event.query ? users.filter((x) => x.name.startsWith(event.query)) : users);
	};

	return (
		<>
			<Head>
				<title>IELTS GPT | Stats</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>
			<main className="w-full h-full min-h-[100vh] flex flex-col items-center bg-neutral-100 text-neutral-600">
				<Navbar userType={user.type} profilePicture={user.profilePicture} />
				<div className="w-full h-full flex flex-col items-center justify-center p-4 relative gap-8">
					{!isLoading && user.type !== "student" && (
						<AutoComplete
							value={autocompleteValue}
							suggestions={items}
							field="name"
							onChange={(e) => setAutocompleteValue(e.target.value)}
							completeMethod={search}
							onSelect={(e) => setSelectedUser(e.value)}
							dropdown
						/>
					)}

					<section className="flex flex-col gap-2 md:gap-4 w-full">
						<div className="flex flex-col">
							<span className="font-semibold">Module Statistics</span>
							<Divider />
						</div>
						<div className="flex flex-col md:grid md:grid-cols-3 w-full gap-4">
							{!isStatsLoading && stats && (
								<>
									<div className="max-w-lg">
										<SingleDatasetChart
											type="polarArea"
											data={formatModuleTotalStats(stats)}
											title="Exams per Module"
											label="Total"
										/>
									</div>
									<div className="max-w-lg">
										<SingleDatasetChart
											type="polarArea"
											data={formatModuleAverageScoreStats(stats)}
											title="Average Score per Module"
											label="Score (in %)"
										/>
									</div>
									<div className="max-w-lg">
										<SingleDatasetChart type="polarArea" data={formatModuleTotalStats(stats)} title="Total exams" />
									</div>
								</>
							)}
						</div>
					</section>

					<section className="flex flex-col gap-2 md:gap-4 w-full">
						<div className="flex flex-col">
							<span className="font-semibold">Exam Statistics</span>
							<Divider />
						</div>

						<div className="flex flex-col md:grid md:grid-cols-3 w-full gap-4">
							{!isStatsLoading && stats && (
								<>
									<div className="max-w-lg">
										<SingleDatasetChart
											type="polarArea"
											data={formatExerciseTotalStats(stats)}
											title="Exercises per Type"
											label="Total"
											colors={chartColors}
										/>
									</div>
									<div className="max-w-lg">
										<SingleDatasetChart
											type="polarArea"
											data={formatExerciseAverageScoreStats(stats)}
											title="Average Score by Exercise"
											label="Average"
											colors={chartColors}
										/>
									</div>
								</>
							)}
						</div>
					</section>
				</div>
			</main>
		</>
	);
}
