/* eslint-disable @next/next/no-img-element */
import Modal from "@/components/Modal";
import useFilterRecordsByUser from "@/hooks/useFilterRecordsByUser";
import useUsers from "@/hooks/useUsers";
import {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,
	BsBriefcaseFill,
	BsGlobeCentralSouthAsia,
	BsPerson,
	BsPersonFill,
	BsPencilSquare,
	BsBank,
	BsCurrencyDollar,
	BsLayoutWtf,
	BsLayoutSidebar,
} from "react-icons/bs";
import UserCard from "@/components/UserCard";
import useGroups from "@/hooks/useGroups";
import IconCard from "./IconCard";
import useFilterStore from "@/stores/listFilterStore";
import {useRouter} from "next/router";
import usePaymentStatusUsers from "@/hooks/usePaymentStatusUsers";
import CorporateStudentsLevels from "./CorporateStudentsLevels";

interface Props {
	user: User;
}

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

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

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

const agentsHash = {
	type: "agent",
	size: 25,
	orderBy: "registrationDate",
};

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

	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 {users: agents, total: totalAgents, reload: reloadAgents, isLoading: isAgentsLoading} = useUsers(agentsHash);

	const {groups} = useGroups({});
	const {pending, done} = usePaymentStatusUsers();

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

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

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

		return (
			<UserList
				user={user}
				type="student"
				filters={[filter]}
				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>
				)}
			/>
		);
	};

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

		return (
			<UserList
				user={user}
				type="teacher"
				filters={[filter]}
				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>
				)}
			/>
		);
	};

	const AgentsList = () => {
		return (
			<UserList
				user={user}
				type="agent"
				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">Country Managers ({total})</h2>
					</div>
				)}
			/>
		);
	};

	const CorporateList = () => (
		<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>
			)}
		/>
	);

	const CorporatePaidStatusList = ({paid}: {paid: Boolean}) => {
		const list = paid ? done : pending;
		const filter = (x: User) => list.includes(x.id);

		return (
			<UserList
				user={user}
				type="corporate"
				filters={[filter]}
				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">
							{paid ? "Payment Done" : "Pending Payment"} ({total})
						</h2>
					</div>
				)}
			/>
		);
	};

	const InactiveCountryManagerList = () => {
		return (
			<UserList
				user={user}
				type="agent"
				filters={[inactiveCountryManagerFilter]}
				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">Inactive Country Managers ({total})</h2>
					</div>
				)}
			/>
		);
	};

	const InactiveStudentsList = () => {
		const filter = (x: User) => x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate);

		return (
			<UserList
				user={user}
				type="student"
				filters={[filter]}
				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">Inactive Students ({total})</h2>
					</div>
				)}
			/>
		);
	};

	const InactiveCorporateList = () => {
		const filter = (x: User) => x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate);

		return (
			<UserList
				user={user}
				filters={[filter]}
				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">Inactive Corporate ({total})</h2>
					</div>
				)}
			/>
		);
	};

	const CorporateStudentsLevelsHelper = () => {
		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">Corporate Students Levels</h2>
				</div>
				<CorporateStudentsLevels />
			</>
		);
	};

	const DefaultDashboard = () => (
		<>
			<section className="w-full grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 place-items-center items-center justify-between">
				<IconCard
					Icon={BsPersonFill}
					isLoading={isStudentsLoading}
					label="Students"
					value={totalStudents}
					onClick={() => router.push("/#students")}
					color="purple"
				/>
				<IconCard
					Icon={BsPencilSquare}
					isLoading={isTeachersLoading}
					label="Teachers"
					value={totalTeachers}
					onClick={() => router.push("/#teachers")}
					color="purple"
				/>
				<IconCard
					Icon={BsBank}
					isLoading={isCorporatesLoading}
					label="Corporate"
					value={totalCorporate}
					onClick={() => router.push("/#corporate")}
					color="purple"
				/>
				<IconCard
					Icon={BsBriefcaseFill}
					isLoading={isAgentsLoading}
					label="Country Managers"
					value={totalAgents}
					onClick={() => router.push("/#agents")}
					color="purple"
				/>
				<IconCard
					Icon={BsGlobeCentralSouthAsia}
					isLoading={isAgentsLoading}
					label="Countries"
					value={[...new Set(agents.filter((x) => x.demographicInformation).map((x) => x.demographicInformation?.country))].length}
					color="purple"
				/>
				<IconCard
					onClick={() => router.push("/#inactiveStudents")}
					Icon={BsPersonFill}
					isLoading={isStudentsLoading}
					label="Inactive Students"
					value={
						students.filter((x) => x.type === "student" && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate)))
							.length
					}
					color="rose"
				/>
				<IconCard
					onClick={() => router.push("/#inactiveCountryManagers")}
					Icon={BsBriefcaseFill}
					isLoading={isAgentsLoading}
					label="Inactive Country Managers"
					value={agents.filter(inactiveCountryManagerFilter).length}
					color="rose"
				/>
				<IconCard
					onClick={() => router.push("/#inactiveCorporate")}
					Icon={BsBank}
					isLoading={isCorporatesLoading}
					label="Inactive Corporate"
					value={
						corporates.filter(
							(x) => x.type === "corporate" && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate)),
						).length
					}
					color="rose"
				/>
				<IconCard
					onClick={() => router.push("/#paymentdone")}
					Icon={BsCurrencyDollar}
					label="Payment Done"
					value={done.length}
					color="purple"
				/>
				<IconCard
					onClick={() => router.push("/#paymentpending")}
					Icon={BsCurrencyDollar}
					label="Pending Payment"
					value={pending.length}
					color="rose"
				/>
				<IconCard
					onClick={() => router.push("https://cms.encoach.com/admin")}
					Icon={BsLayoutSidebar}
					label="Content Management System (CMS)"
					color="green"
				/>
				<IconCard
					onClick={() => router.push("/#corporatestudentslevels")}
					Icon={BsPersonFill}
					isLoading={isStudentsLoading}
					label="Corporate Students Levels"
					color="purple"
				/>
			</section>

			<section className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 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) => {
								return 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">
						{corporates
							.sort((a, b) => {
								return 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">Unpaid Corporate</span>
					<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
						{corporates
							.filter((x) => x.status === "paymentDue")
							.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">Students expiring in 1 month</span>
					<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
						{students
							.filter(
								(x) =>
									x.subscriptionExpirationDate &&
									moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) &&
									moment().isBefore(moment(x.subscriptionExpirationDate)),
							)
							.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">Teachers expiring in 1 month</span>
					<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
						{teachers
							.filter(
								(x) =>
									x.subscriptionExpirationDate &&
									moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) &&
									moment().isBefore(moment(x.subscriptionExpirationDate)),
							)
							.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">Country Manager expiring in 1 month</span>
					<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
						{agents
							.filter(
								(x) =>
									x.subscriptionExpirationDate &&
									moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) &&
									moment().isBefore(moment(x.subscriptionExpirationDate)),
							)
							.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">Corporate expiring in 1 month</span>
					<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
						{corporates
							.filter(
								(x) =>
									x.subscriptionExpirationDate &&
									moment().isAfter(moment(x.subscriptionExpirationDate).subtract(30, "days")) &&
									moment().isBefore(moment(x.subscriptionExpirationDate)),
							)
							.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">Expired Students</span>
					<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
						{students
							.filter((x) => x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)))
							.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">Expired Teachers</span>
					<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
						{teachers
							.filter((x) => x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)))
							.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">Expired Country Manager</span>
					<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
						{agents
							.filter((x) => x.subscriptionExpirationDate && moment().isAfter(moment(x.subscriptionExpirationDate)))
							.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">Expired Corporate</span>
					<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
						{corporates
							.filter((x) => x.subscriptionExpirationDate && moment().isAfter(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 && selectedUser!.type === "student") reloadStudents();
									if (shouldReload && selectedUser!.type === "teacher") reloadTeachers();
									if (shouldReload && selectedUser!.type === "corporate") reloadCorporates();
									if (shouldReload && selectedUser!.type === "agent") reloadAgents();
								}}
								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
								}
								onViewCorporate={
									selectedUser.type === "teacher" || selectedUser.type === "student"
										? () => {
												appendUserFilters({
													id: "view-corporate",
													filter: (x: User) => x.type === "corporate",
												});
												appendUserFilters({
													id: "belongs-to-admin",
													filter: (x: User) =>
														groups
															.filter((g) => g.participants.includes(selectedUser.id))
															.flatMap((g) => [g.admin, ...g.participants])
															.includes(x.id),
												});

												router.push("/list/users");
										  }
										: undefined
								}
								user={selectedUser}
							/>
						</div>
					)}
				</>
			</Modal>
			{router.asPath === "/#students" && <StudentsList />}
			{router.asPath === "/#teachers" && <TeachersList />}
			{router.asPath === "/#corporate" && <CorporateList />}
			{router.asPath === "/#agents" && <AgentsList />}
			{router.asPath === "/#inactiveStudents" && <InactiveStudentsList />}
			{router.asPath === "/#inactiveCorporate" && <InactiveCorporateList />}
			{router.asPath === "/#inactiveCountryManagers" && <InactiveCountryManagerList />}
			{router.asPath === "/#paymentdone" && <CorporatePaidStatusList paid={true} />}
			{router.asPath === "/#paymentpending" && <CorporatePaidStatusList paid={false} />}
			{router.asPath === "/#corporatestudentslevels" && <CorporateStudentsLevelsHelper />}
			{router.asPath === "/" && <DefaultDashboard />}
		</>
	);
}
