/* 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 {ToastContainer} from "react-toastify";
import Layout from "@/components/High/Layout";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import {use, 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 Select from "@/components/Low/Select";
import useUsers from "@/hooks/useUsers";
import useGroups from "@/hooks/useGroups";
import {ITrainingContent} from "@/training/TrainingInterfaces";
import moment from "moment";
import {uuidv4} from "@firebase/util";
import TrainingScore from "@/training/TrainingScore";
import ModuleBadge from "@/components/ModuleBadge";

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 defaultSelectableCorporate = {
	value: "",
	label: "All",
};

const Training: React.FC<{user: User}> = ({user}) => {
	// Record stuff
	const {users} = useUsers();
	const [selectedCorporate, setSelectedCorporate] = useState<string>(defaultSelectableCorporate.value);
	const [statsUserId, setStatsUserId, setRecordTraining] = useRecordStore((state) => [
		state.selectedUser,
		state.setSelectedUser,
		state.setTraining,
	]);
	const {groups: allGroups} = useGroups({});
	const groups = allGroups.filter((x) => x.admin === user.id);
	const [filter, setFilter] = useState<"months" | "weeks" | "days">();

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

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

	useEffect(() => {
		const handleRouteChange = (url: string) => {
			setTrainingStats([]);
		};
		router.events.on("routeChangeStart", handleRouteChange);
		return () => {
			router.events.off("routeChangeStart", handleRouteChange);
		};
	}, [router.events, setTrainingStats]);

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

		if (isNewContentLoading) {
			postStats().then((id) => {
				setTrainingStats([]);
				if (id) {
					router.push(`/training/${id}`);
				}
			});
		}
	}, [isNewContentLoading]);

	useEffect(() => {
		const loadTrainingContent = async () => {
			try {
				const response = await axios.get<ITrainingContent[]>("/api/training");
				setTrainingContent(response.data);
				setIsLoading(false);
			} catch (error) {
				setTrainingContent([]);
				setIsLoading(false);
			}
		};
		loadTrainingContent();
	}, []);

	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);
		}
	}, [trainingContent]);

	// Record Stuff
	const selectableCorporates = [
		defaultSelectableCorporate,
		...users
			.filter((x) => x.type === "corporate")
			.map((x) => ({
				value: x.id,
				label: `${x.name} - ${x.email}`,
			})),
	];

	const getUsersList = (): User[] => {
		if (selectedCorporate) {
			// get groups for that corporate
			const selectedCorporateGroups = allGroups.filter((x) => x.admin === selectedCorporate);

			// get the teacher ids for that group
			const selectedCorporateGroupsParticipants = selectedCorporateGroups.flatMap((x) => x.participants);

			//   // search for groups for these teachers
			//   const teacherGroups = allGroups.filter((x) => {
			//     return selectedCorporateGroupsParticipants.includes(x.admin);
			//   });

			//   const usersList = [
			//     ...selectedCorporateGroupsParticipants,
			//     ...teacherGroups.flatMap((x) => x.participants),
			//   ];
			const userListWithUsers = selectedCorporateGroupsParticipants.map((x) => users.find((y) => y.id === x)) as User[];
			return userListWithUsers.filter((x) => x);
		}

		return users || [];
	};

	const corporateFilteredUserList = getUsersList();
	const getSelectedUser = () => {
		if (selectedCorporate) {
			const userInCorporate = corporateFilteredUserList.find((x) => x.id === statsUserId);
			return userInCorporate || corporateFilteredUserList[0];
		}

		return users.find((x) => x.id === statsUserId) || user;
	};

	const selectedUser = getSelectedUser();
	const selectedUserSelectValue = selectedUser
		? {
				value: selectedUser.id,
				label: `${selectedUser.name} - ${selectedUser.email}`,
		  }
		: {
				value: "",
				label: "",
		  };

	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 || isLoading ? (
					<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>
				) : (
					<>
						<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") && (
									<>
										<label className="font-normal text-base text-mti-gray-dim">Corporate</label>

										<Select
											options={selectableCorporates}
											value={selectableCorporates.find((x) => x.value === selectedCorporate)}
											onChange={(value) => setSelectedCorporate(value?.value || "")}
											styles={{
												menuPortal: (base) => ({...base, zIndex: 9999}),
												option: (styles, state) => ({
													...styles,
													backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
													color: state.isFocused ? "black" : styles.color,
												}),
											}}></Select>
										<label className="font-normal text-base text-mti-gray-dim">User</label>

										<Select
											options={corporateFilteredUserList.map((x) => ({
												value: x.id,
												label: `${x.name} - ${x.email}`,
											}))}
											value={selectedUserSelectValue}
											onChange={(value) => setStatsUserId(value?.value!)}
											styles={{
												menuPortal: (base) => ({...base, zIndex: 9999}),
												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 && (
									<>
										<label className="font-normal text-base text-mti-gray-dim">User</label>

										<Select
											options={users
												.filter((x) => groups.flatMap((y) => y.participants).includes(x.id))
												.map((x) => ({
													value: x.id,
													label: `${x.name} - ${x.email}`,
												}))}
											value={selectedUserSelectValue}
											onChange={(value) => setStatsUserId(value?.value!)}
											styles={{
												menuPortal: (base) => ({...base, zIndex: 9999}),
												option: (styles, state) => ({
													...styles,
													backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
													color: state.isFocused ? "black" : styles.color,
												}),
											}}
										/>
									</>
								)}
								{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>
									</>
								)}
							</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 === "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>
						{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>
						)}
						{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;
