/* eslint-disable @next/next/no-img-element */
import Modal from "@/components/Modal";
import useFilterRecordsByUser from "@/hooks/useFilterRecordsByUser";
import useUsers from "@/hooks/useUsers";
import {CorporateUser, MasterCorporateUser, Stat, User} from "@/interfaces/user";
import UserList from "@/pages/(admin)/Lists/UserList";
import {dateSorter} from "@/utils";
import moment from "moment";
import {useEffect, useState, useMemo} from "react";
import {
	BsArrowLeft,
	BsClipboard2Data,
	BsClock,
	BsPaperclip,
	BsPersonFill,
	BsPencilSquare,
	BsPersonCheck,
	BsPeople,
	BsBank,
	BsEnvelopePaper,
	BsArrowRepeat,
	BsPersonFillGear,
	BsDatabase,
} from "react-icons/bs";
import UserCard from "@/components/UserCard";
import useGroups from "@/hooks/useGroups";

import {averageLevelCalculator, calculateAverageLevel} from "@/utils/score";
import {groupByExam} from "@/utils/stats";
import IconCard from "../IconCard";
import GroupList from "@/pages/(admin)/Lists/GroupList";
import useFilterStore from "@/stores/listFilterStore";
import {useRouter} from "next/router";
import useAssignments from "@/hooks/useAssignments";
import {Assignment} from "@/interfaces/results";
import clsx from "clsx";
import {getCorporateUser} from "@/resources/user";
import {groupBy, uniqBy} from "lodash";
import MasterStatistical from "./MasterStatistical";
import {activeAssignmentFilter} from "@/utils/assignments";
import useUserBalance from "@/hooks/useUserBalance";
import AssignmentsPage from "../views/AssignmentsPage";
import StudentPerformanceList from "./StudentPerformanceList";
import StudentPerformancePage from "./StudentPerformancePage";
import MasterStatisticalPage from "./MasterStatisticalPage";

interface Props {
	user: MasterCorporateUser;
}

const studentHash = {
	type: "student",
	size: 25,
	orderBy: "registrationDate",
};

const teacherHash = {
	type: "teacher",
	size: 25,
	orderBy: "registrationDate",
};

const corporateHash = {
	type: "corporate",
	size: 25,
	orderBy: "registrationDate",
};

export default function MasterCorporateDashboard({user}: Props) {
	const [selectedUser, setSelectedUser] = useState<User>();
	const [showModal, setShowModal] = useState(false);
	const [corporateAssignments, setCorporateAssignments] = useState<(Assignment & {corporate?: CorporateUser})[]>([]);

	const {data: stats} = useFilterRecordsByUser<Stat[]>();

	const {users: students, total: totalStudents, reload: reloadStudents, isLoading: isStudentsLoading} = useUsers(studentHash);
	const {users: teachers, total: totalTeachers, reload: reloadTeachers, isLoading: isTeachersLoading} = useUsers(teacherHash);
	const {users: corporates, total: totalCorporate, reload: reloadCorporates, isLoading: isCorporatesLoading} = useUsers(corporateHash);

	const {groups} = useGroups({admin: user.id, userType: user.type});
	const {balance} = useUserBalance();

	const {assignments, isLoading: isAssignmentsLoading, reload: reloadAssignments} = useAssignments({corporate: user.id});

	const assignmentsGroups = useMemo(() => groups.filter((x) => x.admin === user.id || x.participants.includes(user.id)), [groups, user.id]);

	const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
	const router = useRouter();

	useEffect(() => {
		setShowModal(!!selectedUser && router.asPath === "/");
	}, [selectedUser, router.asPath]);

	useEffect(() => {
		setCorporateAssignments(
			assignments.filter(activeAssignmentFilter).map((a) => {
				const assigner = [...teachers, ...corporates].find((x) => x.id === a.assigner);

				return {
					...a,
					corporate: assigner ? getCorporateUser(assigner, [...teachers, ...corporates], groups) : undefined,
				};
			}),
		);
	}, [assignments, groups, teachers, corporates]);
	const getStatsByStudent = (user: User) => stats.filter((s) => s.user === user.id);

	const UserDisplay = (displayUser: User) => (
		<div
			onClick={() => setSelectedUser(displayUser)}
			className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300">
			<img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
			<div className="flex flex-col gap-1 items-start">
				<span>{displayUser.name}</span>
				<span className="text-sm opacity-75">{displayUser.email}</span>
			</div>
		</div>
	);

	const {users} = useUsers();

	const groupedByNameCorporates = useMemo(
		() =>
			groupBy(
				users.filter((x) => x.type === "corporate"),
				(x: CorporateUser) => x.corporateInformation?.companyInformation?.name || "N/A",
			) as Record<string, CorporateUser[]>,
		[users],
	);

	const groupedByNameCorporatesKeys = Object.keys(groupedByNameCorporates);

	const GroupsList = () => {
		return (
			<>
				<div className="flex flex-col gap-4">
					<div
						onClick={() => router.push("/")}
						className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
						<BsArrowLeft className="text-xl" />
						<span>Back</span>
					</div>
					<h2 className="text-2xl font-semibold">Groups ({groups.length})</h2>
				</div>

				<GroupList user={user} />
			</>
		);
	};

	if (router.asPath === "/#studentsPerformance") return <StudentPerformancePage user={user} />;
	if (router.asPath === "/#statistical") return <MasterStatisticalPage groupedByNameCorporates={groupedByNameCorporates} />;
	if (router.asPath === "/#groups") return <GroupsList />;

	if (router.asPath === "/#students")
		return (
			<UserList
				user={user}
				type="student"
				renderHeader={(total) => (
					<div className="flex flex-col gap-4">
						<div
							onClick={() => router.push("/")}
							className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
							<BsArrowLeft className="text-xl" />
							<span>Back</span>
						</div>
						<h2 className="text-2xl font-semibold">Students ({total})</h2>
					</div>
				)}
			/>
		);

	if (router.asPath === "/#assignments")
		return (
			<AssignmentsPage
				assignments={assignments}
				corporateAssignments={corporateAssignments}
				groups={assignmentsGroups}
				user={user}
				reloadAssignments={reloadAssignments}
				isLoading={isAssignmentsLoading}
				onBack={() => router.push("/")}
			/>
		);

	if (router.asPath === "/#corporate")
		return (
			<UserList
				user={user}
				type="corporate"
				renderHeader={(total) => (
					<div className="flex flex-col gap-4">
						<div
							onClick={() => router.push("/")}
							className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
							<BsArrowLeft className="text-xl" />
							<span>Back</span>
						</div>
						<h2 className="text-2xl font-semibold">Corporate ({total})</h2>
					</div>
				)}
			/>
		);

	if (router.asPath === "/#students")
		return (
			<UserList
				user={user}
				type="student"
				renderHeader={(total) => (
					<div className="flex flex-col gap-4">
						<div
							onClick={() => router.push("/")}
							className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
							<BsArrowLeft className="text-xl" />
							<span>Back</span>
						</div>
						<h2 className="text-2xl font-semibold">Students ({total})</h2>
					</div>
				)}
			/>
		);

	if (router.asPath === "/#teachers")
		return (
			<UserList
				user={user}
				type="teacher"
				renderHeader={(total) => (
					<div className="flex flex-col gap-4">
						<div
							onClick={() => router.push("/")}
							className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
							<BsArrowLeft className="text-xl" />
							<span>Back</span>
						</div>
						<h2 className="text-2xl font-semibold">Teachers ({total})</h2>
					</div>
				)}
			/>
		);

	return (
		<>
			<Modal isOpen={showModal} onClose={() => setSelectedUser(undefined)}>
				<>
					{selectedUser && (
						<div className="w-full flex flex-col gap-8">
							<UserCard
								maxUserAmount={
									user.type === "mastercorporate"
										? (user.corporateInformation?.companyInformation?.userAmount || 0) - balance
										: undefined
								}
								loggedInUser={user}
								onClose={(shouldReload) => {
									setSelectedUser(undefined);
									if (shouldReload && selectedUser!.type === "student") reloadStudents();
									if (shouldReload && selectedUser!.type === "teacher") reloadTeachers();
									if (shouldReload && selectedUser!.type === "corporate") reloadCorporates();
								}}
								onViewStudents={
									selectedUser.type === "corporate" || selectedUser.type === "teacher"
										? () => {
												appendUserFilters({
													id: "view-students",
													filter: (x: User) => x.type === "student",
												});
												appendUserFilters({
													id: "belongs-to-admin",
													filter: (x: User) =>
														groups
															.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
															.flatMap((g) => g.participants)
															.includes(x.id),
												});

												router.push("/list/users");
										  }
										: undefined
								}
								onViewTeachers={
									selectedUser.type === "corporate" || selectedUser.type === "student"
										? () => {
												appendUserFilters({
													id: "view-teachers",
													filter: (x: User) => x.type === "teacher",
												});
												appendUserFilters({
													id: "belongs-to-admin",
													filter: (x: User) =>
														groups
															.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
															.flatMap((g) => g.participants)
															.includes(x.id),
												});

												router.push("/list/users");
										  }
										: undefined
								}
								user={selectedUser}
							/>
						</div>
					)}
				</>
			</Modal>

			<>
				<section className="flex flex-wrap gap-2 items-center -lg:justify-center lg:justify-between text-center">
					<IconCard
						onClick={() => router.push("/#students")}
						Icon={BsPersonFill}
						isLoading={isStudentsLoading}
						label="Students"
						value={totalStudents}
						color="purple"
					/>
					<IconCard
						onClick={() => router.push("/#teachers")}
						Icon={BsPencilSquare}
						isLoading={isTeachersLoading}
						label="Teachers"
						value={totalTeachers}
						color="purple"
					/>
					<IconCard
						Icon={BsClipboard2Data}
						label="Exams Performed"
						value={stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user)).length}
						color="purple"
					/>
					<IconCard
						Icon={BsPaperclip}
						label="Average Level"
						value={averageLevelCalculator(
							students,
							stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user)),
						).toFixed(1)}
						color="purple"
					/>
					<IconCard onClick={() => router.push("/#groups")} Icon={BsPeople} label="Groups" value={groups.length} color="purple" />
					<IconCard
						Icon={BsPersonCheck}
						label="User Balance"
						value={`${balance}/${user.corporateInformation?.companyInformation?.userAmount || 0}`}
						color="purple"
					/>
					<IconCard
						Icon={BsClock}
						label="Expiration Date"
						value={user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy") : "Unlimited"}
						color="rose"
					/>
					<IconCard
						Icon={BsBank}
						label="Corporate Accounts"
						value={totalCorporate}
						isLoading={isCorporatesLoading}
						color="purple"
						onClick={() => router.push("/#corporate")}
					/>
					<IconCard
						Icon={BsBank}
						label="Corporate"
						value={groupedByNameCorporatesKeys.length}
						isLoading={isCorporatesLoading}
						color="purple"
					/>
					<IconCard
						Icon={BsPersonFillGear}
						isLoading={isStudentsLoading}
						label="Student Performance"
						value={totalStudents}
						color="purple"
						onClick={() => router.push("/#studentsPerformance")}
					/>
					<IconCard
						Icon={BsDatabase}
						label="Master Statistical"
						// value={masterCorporateUserGroups.length}
						color="purple"
						onClick={() => router.push("/#statistical")}
					/>
					<button
						disabled={isAssignmentsLoading}
						onClick={() => router.push("/#assignments")}
						className="bg-white col-span-2 rounded-xl shadow p-4 flex flex-col gap-4 items-center w-96 h-52 justify-center cursor-pointer hover:shadow-xl transition ease-in-out duration-300">
						<BsEnvelopePaper className="text-6xl text-mti-purple-light" />
						<span className="flex flex-col gap-1 items-center text-xl">
							<span className="text-lg">Assignments</span>
							<span className="font-semibold text-mti-purple-light">
								{isAssignmentsLoading ? "Loading..." : assignments.filter((a) => !a.archived).length}
							</span>
						</span>
					</button>
				</section>

				<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
					<div className="bg-white shadow flex flex-col rounded-xl w-full">
						<span className="p-4">Latest students</span>
						<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
							{students
								.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
								.map((x) => (
									<UserDisplay key={x.id} {...x} />
								))}
						</div>
					</div>
					<div className="bg-white shadow flex flex-col rounded-xl w-full">
						<span className="p-4">Latest teachers</span>
						<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
							{teachers
								.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
								.map((x) => (
									<UserDisplay key={x.id} {...x} />
								))}
						</div>
					</div>
					<div className="bg-white shadow flex flex-col rounded-xl w-full">
						<span className="p-4">Highest level students</span>
						<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
							{students
								.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
								.map((x) => (
									<UserDisplay key={x.id} {...x} />
								))}
						</div>
					</div>
					<div className="bg-white shadow flex flex-col rounded-xl w-full">
						<span className="p-4">Highest exam count students</span>
						<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
							{students
								.sort(
									(a, b) =>
										Object.keys(groupByExam(getStatsByStudent(b))).length - Object.keys(groupByExam(getStatsByStudent(a))).length,
								)
								.map((x) => (
									<UserDisplay key={x.id} {...x} />
								))}
						</div>
					</div>
				</section>
			</>
		</>
	);
}
