/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {Stat, User} from "@/interfaces/user";
import {useEffect, useState} from "react";
import useStats from "@/hooks/useStats";
import {convertToUserSolutions, groupByDate} from "@/utils/stats";
import moment from "moment";
import useUsers from "@/hooks/useUsers";
import useExamStore from "@/stores/examStore";
import {Module} from "@/interfaces";
import {ToastContainer} from "react-toastify";
import {useRouter} from "next/router";
import {uniqBy} from "lodash";
import {getExamById} from "@/utils/exams";
import {sortByModule} from "@/utils/moduleUtils";
import Layout from "@/components/High/Layout";
import clsx from "clsx";
import {calculateBandScore} from "@/utils/score";
import {BsBook, BsClipboard, BsHeadphones, BsMegaphone, BsPen} from "react-icons/bs";
import Select from "react-select";
import useGroups from "@/hooks/useGroups";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import useAssignments from "@/hooks/useAssignments";
import {uuidv4} from "@firebase/util";
import { usePDFDownload } from "@/hooks/usePDFDownload";

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,
			},
		};
	}

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

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

export default function History({user}: {user: User}) {
	const [statsUserId, setStatsUserId] = useState<string | undefined>(user.id);
	const [groupedStats, setGroupedStats] = useState<{[key: string]: Stat[]}>();
	const [filter, setFilter] = useState<"months" | "weeks" | "days" | "assignments">();
	const {assignments} = useAssignments({});

	const {users} = useUsers();
	const {stats, isLoading: isStatsLoading} = useStats(statsUserId);
	const {groups} = useGroups(user.id);

	const setExams = useExamStore((state) => state.setExams);
	const setShowSolutions = useExamStore((state) => state.setShowSolutions);
	const setUserSolutions = useExamStore((state) => state.setUserSolutions);
	const setSelectedModules = useExamStore((state) => state.setSelectedModules);
	const router = useRouter();
	const renderPdfIcon = usePDFDownload("stats");

	useEffect(() => {
		if (stats && !isStatsLoading) {
			setGroupedStats(groupByDate(stats));
		}
	}, [stats, isStatsLoading]);

	const toggleFilter = (value: "months" | "weeks" | "days" | "assignments") => {
		setFilter((prev) => (prev === value ? undefined : value));
	};

	const filterStatsByDate = (stats: {[key: string]: Stat[]}) => {
		if (filter && filter !== "assignments") {
			const filterDate = moment()
				.subtract({[filter as string]: 1})
				.format("x");
			const filteredStats: {[key: string]: Stat[]} = {};

			Object.keys(stats).forEach((timestamp) => {
				if (timestamp >= filterDate) filteredStats[timestamp] = stats[timestamp];
			});

			return filteredStats;
		}

		if (filter && filter === "assignments") {
			const filteredStats: {[key: string]: Stat[]} = {};

			Object.keys(stats).forEach((timestamp) => {
				if (stats[timestamp].map((s) => s.assignment === undefined).includes(false))
					filteredStats[timestamp] = [...stats[timestamp].filter((s) => !!s.assignment)];
			});

			return filteredStats;
		}

		return stats;
	};

	const formatTimestamp = (timestamp: string) => {
		const date = moment(parseInt(timestamp));
		const formatter = "YYYY/MM/DD - HH:mm";

		return date.format(formatter);
	};

	const aggregateScoresByModule = (stats: Stat[]): {module: Module; total: number; missing: number; correct: number}[] => {
		const scores: {[key in Module]: {total: number; missing: number; correct: number}} = {
			reading: {
				total: 0,
				correct: 0,
				missing: 0,
			},
			listening: {
				total: 0,
				correct: 0,
				missing: 0,
			},
			writing: {
				total: 0,
				correct: 0,
				missing: 0,
			},
			speaking: {
				total: 0,
				correct: 0,
				missing: 0,
			},
			level: {
				total: 0,
				correct: 0,
				missing: 0,
			},
		};

		stats.forEach((x) => {
			scores[x.module!] = {
				total: scores[x.module!].total + x.score.total,
				correct: scores[x.module!].correct + x.score.correct,
				missing: scores[x.module!].missing + x.score.missing,
			};
		});

		return Object.keys(scores)
			.filter((x) => scores[x as Module].total > 0)
			.map((x) => ({module: x as Module, ...scores[x as Module]}));
	};

	const customContent = (timestamp: string) => {
		if (!groupedStats) return <></>;

		const dateStats = groupedStats[timestamp];
		const correct = dateStats.reduce((accumulator, current) => accumulator + current.score.correct, 0);
		const total = dateStats.reduce((accumulator, current) => accumulator + current.score.total, 0);
		const aggregatedScores = aggregateScoresByModule(dateStats).filter((x) => x.total > 0);
		const assignmentID = dateStats.reduce((_, current) => current.assignment as any, "");
		const assignment = assignments.find((a) => a.id === assignmentID);

		const aggregatedLevels = aggregatedScores.map((x) => ({
			module: x.module,
			level: calculateBandScore(x.correct, x.total, x.module, user.focus),
		}));

		const { timeSpent, session } = dateStats[0];

		const selectExam = () => {
			const examPromises = uniqBy(dateStats, "exam").map((stat) => getExamById(stat.module, stat.exam));

			Promise.all(examPromises).then((exams) => {
				if (exams.every((x) => !!x)) {
					setUserSolutions(convertToUserSolutions(dateStats));
					setShowSolutions(true);
					setExams(exams.map((x) => x!).sort(sortByModule));
					setSelectedModules(
						exams
							.map((x) => x!)
							.sort(sortByModule)
							.map((x) => x!.module),
					);
					router.push("/exercises");
				}
			});
		};

		const textColor = clsx(
			correct / total >= 0.7 && "text-mti-purple",
			correct / total >= 0.3 && correct / total < 0.7 && "text-mti-red",
			correct / total < 0.3 && "text-mti-rose",
		);
		
		const content = (
			<>
				<div className="w-full flex justify-between -md:items-center 2xl:items-center">
					<div className="flex md:flex-col 2xl:flex-row md:gap-1 -md:gap-2 2xl:gap-2 -md:items-center 2xl:items-center">
						<span className="font-medium">{formatTimestamp(timestamp)}</span>
						{timeSpent && (
							<>
								<span className="md:hidden 2xl:flex">• </span>
								<span className="text-sm">{Math.floor(timeSpent / 60)} minutes</span>
							</>
						)}
					</div>
					<div className="flex flex-row gap-2">
						<span
							className={textColor}>
							Level{" "}
							{(aggregatedLevels.reduce((accumulator, current) => accumulator + current.level, 0) / aggregatedLevels.length).toFixed(1)}
						</span>
						{renderPdfIcon(session, textColor, textColor)}
					</div>
				</div>

				<div className="w-full flex flex-col gap-1">
					<div className="grid grid-cols-4 gap-2 place-items-start w-full -md:mt-2">
						{aggregatedLevels.map(({module, level}) => (
							<div
								key={module}
								className={clsx(
									"flex gap-2 items-center w-fit text-white -md:px-4 xl:px-4 md:px-2 py-2 rounded-xl",
									module === "reading" && "bg-ielts-reading",
									module === "listening" && "bg-ielts-listening",
									module === "writing" && "bg-ielts-writing",
									module === "speaking" && "bg-ielts-speaking",
									module === "level" && "bg-ielts-level",
								)}>
								{module === "reading" && <BsBook className="w-4 h-4" />}
								{module === "listening" && <BsHeadphones className="w-4 h-4" />}
								{module === "writing" && <BsPen className="w-4 h-4" />}
								{module === "speaking" && <BsMegaphone className="w-4 h-4" />}
								{module === "level" && <BsClipboard className="w-4 h-4" />}
								<span className="text-sm">{level.toFixed(1)}</span>
							</div>
						))}
					</div>

					{assignment && (
						<span className="font-light text-sm">
							Assignment: {assignment.name}, Teacher: {users.find((u) => u.id === assignment.assigner)?.name}
						</span>
					)}
				</div>
			</>
		);

		return (
			<>
				<div
					key={uuidv4()}
					className={clsx(
						"flex flex-col gap-4 border border-mti-gray-platinum p-4 cursor-pointer rounded-xl transition ease-in-out duration-300 -md:hidden",
						correct / total >= 0.7 && "hover:border-mti-purple",
						correct / total >= 0.3 && correct / total < 0.7 && "hover:border-mti-red",
						correct / total < 0.3 && "hover:border-mti-rose",
					)}
					onClick={selectExam}
					role="button">
					{content}
				</div>
				<div
					key={uuidv4()}
					className={clsx(
						"flex flex-col gap-4 border border-mti-gray-platinum p-4 cursor-pointer rounded-xl transition ease-in-out duration-300 -md:tooltip md:hidden",
						correct / total >= 0.7 && "hover:border-mti-purple",
						correct / total >= 0.3 && correct / total < 0.7 && "hover:border-mti-red",
						correct / total < 0.3 && "hover:border-mti-rose",
					)}
					data-tip="Your screen size is too small to view previous exams."
					role="button">
					{content}
				</div>
			</>
		);
	};

	return (
		<>
			<Head>
				<title>Record | 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}>
					<div className="w-full flex -xl:flex-col -xl:gap-4 justify-between items-center">
						<div className="xl:w-3/4">
							{(user.type === "developer" || user.type === "admin") && (
								<Select
									options={users.map((x) => ({value: x.id, label: `${x.name} - ${x.email}`}))}
									defaultValue={{value: user.id, label: `${user.name} - ${user.email}`}}
									onChange={(value) => setStatsUserId(value?.value)}
									styles={{
										option: (styles, state) => ({
											...styles,
											backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
											color: state.isFocused ? "black" : styles.color,
										}),
									}}
								/>
							)}
							{(user.type === "corporate" || user.type === "teacher") && groups.length > 0 && (
								<Select
									options={users
										.filter((x) => groups.flatMap((y) => y.participants).includes(x.id))
										.map((x) => ({value: x.id, label: `${x.name} - ${x.email}`}))}
									defaultValue={{value: user.id, label: `${user.name} - ${user.email}`}}
									onChange={(value) => setStatsUserId(value?.value)}
									styles={{
										option: (styles, state) => ({
											...styles,
											backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
											color: state.isFocused ? "black" : styles.color,
										}),
									}}
								/>
							)}
						</div>
						<div className="flex gap-4 w-full justify-center xl:justify-end">
							<button
								className={clsx(
									"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
									"transition duration-300 ease-in-out",
									filter === "assignments" && "!bg-mti-purple-light !text-white",
								)}
								onClick={() => toggleFilter("assignments")}>
								Assignments
							</button>
							<button
								className={clsx(
									"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
									"transition duration-300 ease-in-out",
									filter === "months" && "!bg-mti-purple-light !text-white",
								)}
								onClick={() => toggleFilter("months")}>
								Last month
							</button>
							<button
								className={clsx(
									"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
									"transition duration-300 ease-in-out",
									filter === "weeks" && "!bg-mti-purple-light !text-white",
								)}
								onClick={() => toggleFilter("weeks")}>
								Last week
							</button>
							<button
								className={clsx(
									"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
									"transition duration-300 ease-in-out",
									filter === "days" && "!bg-mti-purple-light !text-white",
								)}
								onClick={() => toggleFilter("days")}>
								Last day
							</button>
						</div>
					</div>
					{groupedStats && Object.keys(groupedStats).length > 0 && !isStatsLoading && (
						<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 w-full gap-4 xl:gap-6">
							{Object.keys(filterStatsByDate(groupedStats))
								.sort((a, b) => parseInt(b) - parseInt(a))
								.map(customContent)}
						</div>
					)}
					{groupedStats && Object.keys(groupedStats).length === 0 && !isStatsLoading && (
						<span className="font-semibold ml-1">No record to display...</span>
					)}
				</Layout>
			)}
		</>
	);
}
