/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import { withIronSessionSsr } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { User } from "@/interfaces/user";
import { ToastContainer } from "react-toastify";
import Layout from "@/components/High/Layout";
import { shouldRedirectHome } from "@/utils/navigation.disabled";
import { useEffect, useState } from "react";
import clsx from "clsx";
import { FaPlus } from "react-icons/fa";
import useRecordStore from "@/stores/recordStore";
import router from "next/router";
import useTrainingContentStore from "@/stores/trainingContentStore";
import axios from "axios";
import { ITrainingContent } from "@/training/TrainingInterfaces";
import moment from "moment";
import { uuidv4 } from "@firebase/util";
import TrainingScore from "@/training/TrainingScore";
import ModuleBadge from "@/components/ModuleBadge";
import RecordFilter from "@/components/Medium/RecordFilter";
import useFilterRecordsByUser from "@/hooks/useFilterRecordsByUser";

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

	if (!user || !user.isVerified) {
		return {
			redirect: {
				destination: "/login",
				permanent: false,
			},
		};
	}

	if (shouldRedirectHome(user)) {
		return {
			redirect: {
				destination: "/",
				permanent: false,
			},
		};
	}

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

const Training: React.FC<{ user: User }> = ({ user }) => {
	const [recordUserId, setRecordTraining] = useRecordStore((state) => [
		state.selectedUser,
		state.setTraining,
	]);
	const [filter, setFilter] = useState<"months" | "weeks" | "days" | "assignments">();

	const [stats, setTrainingStats] = useTrainingContentStore((state) => [state.stats, state.setStats]);
	const [isNewContentLoading, setIsNewContentLoading] = useState(stats.length != 0);
	const [groupedByTrainingContent, setGroupedByTrainingContent] = useState<{ [key: string]: ITrainingContent }>();

	const { data: trainingContent, isLoading: areRecordsLoading } = useFilterRecordsByUser<ITrainingContent[]>(recordUserId || user?.id, undefined, "training");

	useEffect(() => {
		const handleRouteChange = (url: string) => {
			setTrainingStats([]);
		};
		router.events.on("routeChangeStart", handleRouteChange);
		return () => {
			router.events.off("routeChangeStart", handleRouteChange);
		};
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [router.events, setTrainingStats]);

	useEffect(() => {
		const postStats = async () => {
			try {
				const response = await axios.post<{ id: string }>(`/api/training`, { userID: user.id, stats: stats });
				return response.data.id;
			} catch (error) {
				setIsNewContentLoading(false);
			}
		};

		if (isNewContentLoading) {
			postStats().then((id) => {
				setTrainingStats([]);
				if (id) {
					router.push(`/training/${id}`);
				}
			});
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [isNewContentLoading]);

	const handleNewTrainingContent = () => {
		setRecordTraining(true);
		router.push("/record");
	};

	const filterTrainingContentByDate = (trainingContent: { [key: string]: ITrainingContent }) => {
		if (filter) {
			const filterDate = moment()
				.subtract({ [filter as string]: 1 })
				.format("x");
			const filteredTrainingContent: { [key: string]: ITrainingContent } = {};

			Object.keys(trainingContent).forEach((timestamp) => {
				if (timestamp >= filterDate) filteredTrainingContent[timestamp] = trainingContent[timestamp];
			});
			return filteredTrainingContent;
		}
		return trainingContent;
	};

	useEffect(() => {
		if (trainingContent.length > 0) {
			const grouped = trainingContent.reduce((acc, content) => {
				acc[content.created_at] = content;
				return acc;
			}, {} as { [key: number]: ITrainingContent });

			setGroupedByTrainingContent(grouped);
		}else {
			setGroupedByTrainingContent(undefined);
		}
	}, [trainingContent]);

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

		return date.format(formatter);
	};

	const selectTrainingContent = (trainingContent: ITrainingContent) => {
		router.push(`/training/${trainingContent.id}`);
	};

	const trainingContentContainer = (timestamp: string) => {
		if (!groupedByTrainingContent) return <></>;
		
		const trainingContent: ITrainingContent = groupedByTrainingContent[timestamp];
		const uniqueModules = [...new Set(trainingContent.exams.map((exam) => exam.module))];

		return (
			<>
				<div
					key={uuidv4()}
					className={clsx(
						"flex flex-col justify-between gap-4 border border-mti-gray-platinum p-4 cursor-pointer rounded-xl transition ease-in-out duration-300 -md:hidden",
					)}
					onClick={() => selectTrainingContent(trainingContent)}
					role="button">
					<div className="w-full flex justify-between -md:items-center 2xl:items-center">
						<div className="flex flex-col md:gap-1 -md:gap-2 2xl:gap-2">
							<span className="font-medium">{formatTimestamp(timestamp)}</span>
						</div>
						<div className="flex flex-col gap-2">
							<div className="w-full flex flex-row gap-1">
								{uniqueModules.map((module) => (
									<ModuleBadge key={module} module={module} />
								))}
							</div>
						</div>
					</div>
					<TrainingScore trainingContent={trainingContent} gridView={true} />
				</div>
			</>
		);
	};

	return (
		<>
			<Head>
				<title>Training | 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 />

			<Layout user={user}>
				{isNewContentLoading || areRecordsLoading ? (
					<div className="absolute left-1/2 top-1/2 flex h-fit w-fit -translate-x-1/2 -translate-y-1/2 animate-pulse flex-col items-center gap-12">
						<span className="loading loading-infinity w-32 bg-mti-green-light" />
						{isNewContentLoading && (
							<span className="text-center text-2xl font-bold text-mti-green-light">Assessing your exams, please be patient...</span>
						)}
					</div>
				) : (
					<>
						<RecordFilter user={user} filterState={{ filter: filter, setFilter: setFilter }} assignments={false} >
							{user.type === "student" && (
								<>
									<div className="flex items-center">
										<div className="font-semibold text-2xl">Generate New Training Material</div>
										<button
											className={clsx(
												"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light ml-4",
												"transition duration-300 ease-in-out",
											)}
											onClick={handleNewTrainingContent}>
											<FaPlus />
										</button>
									</div>
								</>
							)}
						</RecordFilter>
						{trainingContent.length == 0 && (
							<div className="flex flex-grow justify-center items-center">
								<span className="font-semibold ml-1">No training content to display...</span>
							</div>
						)}
						{!areRecordsLoading && groupedByTrainingContent && Object.keys(groupedByTrainingContent).length > 0 && (
							<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-2 2xl:grid-cols-3 w-full gap-4 xl:gap-6">
								{Object.keys(filterTrainingContentByDate(groupedByTrainingContent))
									.sort((a, b) => parseInt(b) - parseInt(a))
									.map(trainingContentContainer)}
							</div>
						)}
					</>
				)}
			</Layout>
		</>
	);
};

export default Training;
