/* eslint-disable @next/next/no-img-element */
import Modal from "@/components/Modal";
import useStats from "@/hooks/useStats";
import useUsers from "@/hooks/useUsers";
import {CorporateUser, Group, Stat, User} from "@/interfaces/user";
import UserList from "@/pages/(admin)/Lists/UserList";
import {dateSorter} from "@/utils";
import moment from "moment";
import {useEffect, useState} from "react";
import {
	BsArrowLeft,
	BsClipboard2Data,
	BsClipboard2DataFill,
	BsClock,
	BsGlobeCentralSouthAsia,
	BsPaperclip,
	BsPerson,
	BsPersonAdd,
	BsPersonFill,
	BsPersonFillGear,
	BsPersonGear,
	BsPencilSquare,
	BsPersonBadge,
	BsPersonCheck,
	BsPeople,
} from "react-icons/bs";
import UserCard from "@/components/UserCard";
import useGroups from "@/hooks/useGroups";
import {calculateAverageLevel, calculateBandScore} from "@/utils/score";
import {MODULE_ARRAY} from "@/utils/moduleUtils";
import {Module} from "@/interfaces";
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 useCodes from "@/hooks/useCodes";

interface Props {
	user: CorporateUser;
}

export default function CorporateDashboard({user}: Props) {
	const [page, setPage] = useState("");
	const [selectedUser, setSelectedUser] = useState<User>();
	const [showModal, setShowModal] = useState(false);

	const {stats} = useStats();
	const {users, reload} = useUsers();
	const {codes} = useCodes(user.id);
	const {groups} = useGroups(user.id);

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

	useEffect(() => {
		setShowModal(!!selectedUser && page === "");
	}, [selectedUser, page]);

	const studentFilter = (user: User) => user.type === "student" && groups.flatMap((g) => g.participants).includes(user.id);
	const teacherFilter = (user: User) => user.type === "teacher" && groups.flatMap((g) => g.participants).includes(user.id);

	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 StudentsList = () => {
		const filter = (x: User) =>
			x.type === "student" &&
			(!!selectedUser
				? groups
						.filter((g) => g.admin === selectedUser.id)
						.flatMap((g) => g.participants)
						.includes(x.id) || false
				: groups.flatMap((g) => g.participants).includes(x.id));

		return (
			<>
				<div className="flex flex-col gap-4">
					<div
						onClick={() => setPage("")}
						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 ({users.filter(filter).length})</h2>
				</div>

				<UserList user={user} filters={[filter]} />
			</>
		);
	};

	const TeachersList = () => {
		const filter = (x: User) =>
			x.type === "teacher" &&
			(!!selectedUser
				? groups
						.filter((g) => g.admin === selectedUser.id)
						.flatMap((g) => g.participants)
						.includes(x.id) || false
				: groups.flatMap((g) => g.participants).includes(x.id));

		return (
			<>
				<div className="flex flex-col gap-4">
					<div
						onClick={() => setPage("")}
						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 ({users.filter(filter).length})</h2>
				</div>

				<UserList user={user} filters={[filter]} />
			</>
		);
	};

	const GroupsList = () => {
		const filter = (x: Group) => x.admin === user.id || x.participants.includes(user.id);

		return (
			<>
				<div className="flex flex-col gap-4">
					<div
						onClick={() => setPage("")}
						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.filter(filter).length})</h2>
				</div>

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

	const averageLevelCalculator = (studentStats: Stat[]) => {
		const formattedStats = studentStats
			.map((s) => ({focus: users.find((u) => u.id === s.user)?.focus, score: s.score, module: s.module}))
			.filter((f) => !!f.focus);
		const bandScores = formattedStats.map((s) => ({
			module: s.module,
			level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
		}));

		const levels: {[key in Module]: number} = {reading: 0, listening: 0, writing: 0, speaking: 0, level: 0};
		bandScores.forEach((b) => (levels[b.module] += b.level));

		return calculateAverageLevel(levels);
	};

	const DefaultDashboard = () => (
		<>
			<section className="flex flex-wrap gap-2 items-center -lg:justify-center lg:justify-between text-center">
				<IconCard
					onClick={() => setPage("students")}
					Icon={BsPersonFill}
					label="Students"
					value={users.filter(studentFilter).length}
					color="purple"
				/>
				<IconCard
					onClick={() => setPage("teachers")}
					Icon={BsPencilSquare}
					label="Teachers"
					value={users.filter(teacherFilter).length}
					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(stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user))).toFixed(1)}
					color="purple"
				/>
				<IconCard onClick={() => setPage("groups")} Icon={BsPeople} label="Groups" value={groups.length} color="purple" />
				<IconCard
					Icon={BsPersonCheck}
					label="User Balance"
					value={`${codes.length}/${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"
				/>
			</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">
						{users
							.filter(studentFilter)
							.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">
						{users
							.filter(teacherFilter)
							.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">
						{users
							.filter(studentFilter)
							.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">
						{users
							.filter(studentFilter)
							.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>
		</>
	);

	return (
		<>
			<Modal isOpen={showModal} onClose={() => setSelectedUser(undefined)}>
				<>
					{selectedUser && (
						<div className="w-full flex flex-col gap-8">
							<UserCard
								loggedInUser={user}
								onClose={(shouldReload) => {
									setSelectedUser(undefined);
									if (shouldReload) reload();
								}}
								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>
			{page === "students" && <StudentsList />}
			{page === "teachers" && <TeachersList />}
			{page === "groups" && <GroupsList />}
			{page === "" && <DefaultDashboard />}
		</>
	);
}
