import Layout from "@/components/High/Layout";
import AssignmentCard from "@/dashboards/AssignmentCard";
import AssignmentView from "@/dashboards/AssignmentView";
import {Assignment} from "@/interfaces/results";
import {CorporateUser, Group, User} from "@/interfaces/user";
import {sessionOptions} from "@/lib/session";
import {getUserCompanyName} from "@/resources/user";
import {mapBy, serialize} from "@/utils";
import {
	activeAssignmentFilter,
	archivedAssignmentFilter,
	futureAssignmentFilter,
	pastAssignmentFilter,
	startHasExpiredAssignmentFilter,
} from "@/utils/assignments";
import {getEntitiesAssignments} from "@/utils/assignments.be";
import {getEntitiesWithRoles} from "@/utils/entities.be";
import {getGroupsByEntities} from "@/utils/groups.be";
import {checkAccess} from "@/utils/permissions";
import {getEntitiesUsers} from "@/utils/users.be";
import {withIronSessionSsr} from "iron-session/next";
import {groupBy} from "lodash";
import Link from "next/link";
import {useRouter} from "next/router";
import {useMemo, useState} from "react";
import {BsChevronLeft, BsPlus} from "react-icons/bs";

export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
	const user = req.session.user as User | undefined;

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

	if (!checkAccess(user, ["admin", "developer", "corporate", "teacher", "mastercorporate"]))
		return {
			redirect: {
				destination: "/dashboard",
				permanent: false,
			},
		};

	const entityIDS = mapBy(user.entities, "id") || [];

	const users = await getEntitiesUsers(entityIDS);
	const entities = await getEntitiesWithRoles(entityIDS);
	const assignments = await getEntitiesAssignments(entityIDS);
	const groups = await getGroupsByEntities(entityIDS);

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

interface Props {
	assignments: Assignment[];
	corporateAssignments?: ({corporate?: CorporateUser} & Assignment)[];
	groups: Group[];
	user: User;
	users: User[];
}

export default function AssignmentsPage({assignments, corporateAssignments, user, users, groups}: Props) {
	const [selectedAssignment, setSelectedAssignment] = useState<Assignment>();
	const [isCreatingAssignment, setIsCreatingAssignment] = useState(false);

	const displayAssignmentView = useMemo(() => !!selectedAssignment && !isCreatingAssignment, [selectedAssignment, isCreatingAssignment]);

	const assignmentsPastExpiredStart = assignments.filter(startHasExpiredAssignmentFilter);

	const router = useRouter();

	return (
		<Layout user={user}>
			{displayAssignmentView && (
				<AssignmentView
					users={users}
					isOpen={displayAssignmentView}
					onClose={() => {
						setSelectedAssignment(undefined);
						setIsCreatingAssignment(false);
					}}
					assignment={selectedAssignment}
				/>
			)}
			<div className="w-full flex justify-between items-center">
				<div className="flex items-center gap-2">
					<Link href="/dashboard" className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
						<BsChevronLeft />
					</Link>
					<h2 className="font-bold text-2xl">Assignments</h2>
				</div>
			</div>
			<div className="flex flex-col gap-2">
				<span className="text-lg font-bold">Active Assignments Status</span>
				<div className="flex items-center gap-4">
					<span>
						<b>Total:</b> {assignments.filter(activeAssignmentFilter).reduce((acc, curr) => acc + curr.results.length, 0)}/
						{assignments.filter(activeAssignmentFilter).reduce((acc, curr) => curr.exams.length + acc, 0)}
					</span>
					{Object.keys(groupBy(corporateAssignments, (x) => x.corporate?.id)).map((x) => (
						<div key={x}>
							<span className="font-semibold">{getUserCompanyName(users.find((u) => u.id === x)!, users, groups)}: </span>
							<span>
								{groupBy(corporateAssignments, (x) => x.corporate?.id)[x].reduce((acc, curr) => curr.results.length + acc, 0)}/
								{groupBy(corporateAssignments, (x) => x.corporate?.id)[x].reduce((acc, curr) => curr.exams.length + acc, 0)}
							</span>
						</div>
					))}
				</div>
			</div>
			<section className="flex flex-col gap-4">
				<h2 className="text-2xl font-semibold">Active Assignments ({assignments.filter(activeAssignmentFilter).length})</h2>
				<div className="flex flex-wrap gap-2">
					{assignments.filter(activeAssignmentFilter).map((a) => (
						<AssignmentCard {...a} users={users} onClick={() => setSelectedAssignment(a)} key={a.id} />
					))}
				</div>
			</section>
			<section className="flex flex-col gap-4">
				<h2 className="text-2xl font-semibold">Planned Assignments ({assignments.filter(futureAssignmentFilter).length})</h2>
				<div className="flex flex-wrap gap-2">
					<Link
						href="/assignments/creator"
						className="w-[250px] h-[200px] flex flex-col gap-2 items-center justify-center bg-white hover:bg-mti-purple-ultralight text-mti-purple-light hover:text-mti-purple-dark border border-mti-gray-platinum hover:drop-shadow p-4 cursor-pointer rounded-xl transition ease-in-out duration-300">
						<BsPlus className="text-6xl" />
						<span className="text-lg">New Assignment</span>
					</Link>
					{assignments.filter(futureAssignmentFilter).map((a) => (
						<AssignmentCard {...a} users={users} onClick={() => router.push(`/assignments/creator/${a.id}`)} key={a.id} />
					))}
				</div>
			</section>
			<section className="flex flex-col gap-4">
				<h2 className="text-2xl font-semibold">Past Assignments ({assignments.filter(pastAssignmentFilter).length})</h2>
				<div className="flex flex-wrap gap-2">
					{assignments.filter(pastAssignmentFilter).map((a) => (
						<AssignmentCard
							{...a}
							users={users}
							onClick={() => setSelectedAssignment(a)}
							key={a.id}
							allowDownload
							allowArchive
							allowExcelDownload
						/>
					))}
				</div>
			</section>
			<section className="flex flex-col gap-4">
				<h2 className="text-2xl font-semibold">Assignments start expired ({assignmentsPastExpiredStart.length})</h2>
				<div className="flex flex-wrap gap-2">
					{assignments.filter(startHasExpiredAssignmentFilter).map((a) => (
						<AssignmentCard
							{...a}
							users={users}
							onClick={() => setSelectedAssignment(a)}
							key={a.id}
							allowDownload
							allowArchive
							allowExcelDownload
						/>
					))}
				</div>
			</section>
			<section className="flex flex-col gap-4">
				<h2 className="text-2xl font-semibold">Archived Assignments ({assignments.filter(archivedAssignmentFilter).length})</h2>
				<div className="flex flex-wrap gap-2">
					{assignments.filter(archivedAssignmentFilter).map((a) => (
						<AssignmentCard
							{...a}
							users={users}
							onClick={() => setSelectedAssignment(a)}
							key={a.id}
							allowDownload
							allowUnarchive
							allowExcelDownload
						/>
					))}
				</div>
			</section>
		</Layout>
	);
}
