import useFilterRecordsByUser from "@/hooks/useFilterRecordsByUser";
import useGroups from "@/hooks/useGroups";
import useUsers, {userHashStudent} from "@/hooks/useUsers";
import {Group, Stat, StudentUser, User} from "@/interfaces/user";
import {getUserCompanyName} from "@/resources/user";
import clsx from "clsx";
import {useRouter} from "next/router";
import {BsArrowLeft, BsArrowRepeat, BsChevronLeft} from "react-icons/bs";
import { mapBy, serialize } from "@/utils";
import {withIronSessionSsr} from "iron-session/next";
import { getEntitiesUsers, getUsers } from "@/utils/users.be";
import { sessionOptions } from "@/lib/session";
import { checkAccess } from "@/utils/permissions";
import { getEntities } from "@/utils/entities.be";
import { Entity } from "@/interfaces/entity";
import { getParticipantGroups, getParticipantsGroups } from "@/utils/groups.be";
import StudentPerformanceList from "../(admin)/Lists/StudentPerformanceList";
import Head from "next/head";
import { ToastContainer } from "react-toastify";
import Layout from "@/components/High/Layout";
import { requestUser } from "@/utils/api";
import { redirect } from "@/utils";

export const getServerSideProps = withIronSessionSsr(async ({req, res, query}) => {
	const user = await requestUser(req, res)
	if (!user) return redirect("/login")

	const entityIDs = mapBy(user.entities, 'id')

	const entities = await getEntities(checkAccess(user, ["admin", 'developer']) ? undefined : entityIDs)
	const students = await (checkAccess(user, ["admin", 'developer'])
		? getUsers({type: 'student'})
		: getEntitiesUsers(entityIDs, {type: 'student'})
	)
	const groups = await getParticipantsGroups(mapBy(students, 'id'))

	return {
		props: serialize({user, students, entities, groups}),
	};
}, sessionOptions);

interface Props {
	user: User;
	students: StudentUser[]
	entities: Entity[]
	groups: Group[]
}

const StudentPerformance = ({user, students, entities, groups}: Props) => {
	const {data: stats} = useFilterRecordsByUser<Stat[]>();

	const router = useRouter();

	const performanceStudents = students.map((u) => ({
		...u,
		group: groups.find((x) => x.participants.includes(u.id))?.name || "N/A",
		entitiesLabel: mapBy(u.entities, 'id').map((id) => entities.find((e) => e.id === id)?.label).filter((e) => !!e).join(', '),
	}));

	return (
	<>
			<Head>
				<title>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}>
				<div className="flex items-center gap-2">
					<button
						onClick={() => {
							router.back()
						}}
						className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
						<BsChevronLeft />
					</button>
					<h2 className="font-bold text-2xl">Student Performance ({ students.length })</h2>
				</div>
			<StudentPerformanceList items={performanceStudents} stats={stats} />
			</Layout>
		</>
	);
};

export default StudentPerformance;
