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

interface Props {
	user: User;
}

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

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

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

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

	// eslint-disable-next-line react-hooks/exhaustive-deps
	useEffect(reload, [page]);

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

		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 || g.participants.includes(selectedUser.id))
						.flatMap((g) => g.participants)
						.includes(x.id) || false
				: true);

		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 AgentsList = () => {
		const filter = (x: User) => x.type === "agent";

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

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

	const CorporateList = () => (
		<>
			<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">Corporate ({users.filter((x) => x.type === "corporate").length})</h2>
			</div>

			<UserList user={user} filters={[(x) => x.type === "corporate"]} />
		</>
	);

	const InactiveCountryManagerList = () => {
		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 Country Managers ({users.filter(inactiveCountryManagerFilter).length})</h2>
				</div>

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

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

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

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

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

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

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

	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}
					label="Students"
					value={users.filter((x) => x.type === "student").length}
					onClick={() => setPage("students")}
					color="purple"
				/>
				<IconCard
					Icon={BsPencilSquare}
					label="Teachers"
					value={users.filter((x) => x.type === "teacher").length}
					onClick={() => setPage("teachers")}
					color="purple"
				/>
				<IconCard
					Icon={BsBank}
					label="Corporate"
					value={users.filter((x) => x.type === "corporate").length}
					onClick={() => setPage("corporate")}
					color="purple"
				/>
				<IconCard
					Icon={BsBriefcaseFill}
					label="Country Managers"
					value={users.filter((x) => x.type === "agent").length}
					onClick={() => setPage("agents")}
					color="purple"
				/>
				<IconCard
					Icon={BsGlobeCentralSouthAsia}
					label="Countries"
					value={[...new Set(users.filter((x) => x.demographicInformation).map((x) => x.demographicInformation?.country))].length}
					color="purple"
				/>
				<IconCard
					onClick={() => setPage("inactiveStudents")}
					Icon={BsPerson}
					label="Inactive Students"
					value={
						users.filter((x) => x.type === "student" && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate)))
							.length
					}
					color="rose"
				/>
				<IconCard
					onClick={() => setPage("inactiveCountryManagers")}
					Icon={BsPerson}
					label="Inactive Country Managers"
					value={users.filter(inactiveCountryManagerFilter).length}
					color="rose"
				/>
				<IconCard
					onClick={() => setPage("inactiveCorporate")}
					Icon={BsPerson}
					label="Inactive Corporate"
					value={
						users.filter((x) => x.type === "corporate" && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate)))
							.length
					}
					color="rose"
				/>
			</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">
						{users
							.filter((x) => x.type === "student")
							.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((x) => x.type === "corporate")
							.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">Unpaid Corporate</span>
					<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
						{users
							.filter((x) => x.type === "corporate" && 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">
						{users
							.filter(
								(x) =>
									x.type === "student" &&
									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">
						{users
							.filter(
								(x) =>
									x.type === "teacher" &&
									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">
						{users
							.filter(
								(x) =>
									x.type === "corporate" &&
									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">
						{users
							.filter(
								(x) => x.type === "student" && 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">
						{users
							.filter(
								(x) => x.type === "teacher" && 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">
						{users
							.filter(
								(x) =>
									x.type === "corporate" && 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) 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
								}
								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>
			{page === "students" && <StudentsList />}
			{page === "teachers" && <TeachersList />}
			{page === "corporate" && <CorporateList />}
			{page === "agents" && <AgentsList />}
			{page === "inactiveStudents" && <InactiveStudentsList />}
			{page === "inactiveCorporate" && <InactiveCorporateList />}
			{page === "inactiveCountryManagers" && <InactiveCountryManagerList />}
			{page === "" && <DefaultDashboard />}
		</>
	);
}
