/* eslint-disable @next/next/no-img-element */
import Modal from "@/components/Modal";
import useStats from "@/hooks/useStats";
import useUsers from "@/hooks/useUsers";
import {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,
	BsPersonFill,
	BsBank
} 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";

interface Props {
	user: User;
}

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

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

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

	const corporateFilter = (user: User) => user.type === "corporate";
	const referredCorporateFilter = (x: User) =>
		x.type === "corporate" && !!x.corporateInformation && x.corporateInformation.referralAgent === user.id;
	const inactiveReferredCorporateFilter = (x: User) => referredCorporateFilter(x)  && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate));

	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.type === "corporate"
						? displayUser.corporateInformation?.companyInformation?.name || displayUser.name
						: displayUser.name}
				</span>
				<span className="text-sm opacity-75">{displayUser.email}</span>
			</div>
		</div>
	);

	const ReferredCorporateList = () => {
		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">Referred Corporate ({users.filter(referredCorporateFilter).length})</h2>
				</div>

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

	const InactiveReferredCorporateList = () => {
		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">Inactive Referred Corporate ({users.filter(inactiveReferredCorporateFilter).length})</h2>
				</div>

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

	const CorporateList = () => {
		const filter = (x: User) => x.type === "corporate";

		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">Referred Corporate ({users.filter(filter).length})</h2>
				</div>

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

	const DefaultDashboard = () => (
		<>
			<section className="flex flex-wrap gap-2 items-center -lg:justify-center lg:gap-4 text-center">
				<IconCard
					onClick={() => setPage("referredCorporate")}
					Icon={BsPersonFill}
					label="Referred Corporate"
					value={users.filter(referredCorporateFilter).length}
					color="purple"
				/>
				<IconCard
					onClick={() => setPage("inactiveReferredCorporate")}
					Icon={BsPersonFill}
					label="Inactive Referred Corporate"
					value={users.filter(inactiveReferredCorporateFilter).length}
					color="rose"
				/>
				<IconCard
					onClick={() => setPage("corporate")}
					Icon={BsBank}
					label="Corporate"
					value={users.filter(corporateFilter).length}
					color="purple"
				/>
			</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 Referred Corporate</span>
					<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
						{users
							.filter(referredCorporateFilter)
							.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 corporate</span>
					<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
						{users
							.filter(corporateFilter)
							.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">Referenced corporate expiring in 1 month</span>
					<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
						{users
							.filter(
								(x) =>
									referredCorporateFilter(x) &&
									moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) &&
									moment().isBefore(moment(x.subscriptionExpirationDate)),
							)
							.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" ? () => setPage("students") : undefined
								}
								onViewTeachers={selectedUser.type === "corporate" ? () => setPage("teachers") : undefined}
								user={selectedUser}
							/>
						</div>
					)}
				</>
			</Modal>
			{page === "referredCorporate" && <ReferredCorporateList />}
			{page === "corporate" && <CorporateList />}
			{page === "inactiveReferredCorporate" && <InactiveReferredCorporateList />}
			{page === "" && <DefaultDashboard />}
		</>
	);
}
