/* 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;
}

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

	const {data: stats} = useFilterRecordsByUser<Stat[]>(user.id);
	const {users, reload} = useUsers();
	const {groups} = useGroups({});
	const {pending, done} = usePaymentStatusUsers();

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

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

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

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

	const CorporateList = () => (
		<UserList
			user={user}
			filters={[(x) => x.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) => x.type === "corporate" && list.includes(x.id);

		return (
			<UserList
				user={user}
				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}
				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.type === "student" && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate));

		return (
			<UserList
				user={user}
				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.type === "corporate" && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate));

		return (
			<UserList
				user={user}
				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 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}
					label="Students"
					value={users.filter((x) => x.type === "student").length}
					onClick={() => router.push("/#students")}
					color="purple"
				/>
				<IconCard
					Icon={BsPencilSquare}
					label="Teachers"
					value={users.filter((x) => x.type === "teacher").length}
					onClick={() => router.push("/#teachers")}
					color="purple"
				/>
				<IconCard
					Icon={BsBank}
					label="Corporate"
					value={users.filter((x) => x.type === "corporate").length}
					onClick={() => router.push("/#corporate")}
					color="purple"
				/>
				<IconCard
					Icon={BsBriefcaseFill}
					label="Country Managers"
					value={users.filter((x) => x.type === "agent").length}
					onClick={() => router.push("/#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={() => router.push("/#inactiveStudents")}
					Icon={BsPersonFill}
					label="Inactive Students"
					value={
						users.filter((x) => x.type === "student" && (x.status === "disabled" || moment().isAfter(x.subscriptionExpirationDate)))
							.length
					}
					color="rose"
				/>
				<IconCard
					onClick={() => router.push("/#inactiveCountryManagers")}
					Icon={BsBriefcaseFill}
					label="Inactive Country Managers"
					value={users.filter(inactiveCountryManagerFilter).length}
					color="rose"
				/>
				<IconCard
					onClick={() => router.push("/#inactiveCorporate")}
					Icon={BsBank}
					label="Inactive Corporate"
					value={
						users.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}
					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">
						{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 teachers</span>
					<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
						{users
							.filter((x) => x.type === "teacher")
							.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">
						{users
							.filter((x) => x.type === "corporate")
							.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">
						{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">Teachers 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">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 === "agent" &&
									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 Teachers</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 Country Manager</span>
					<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
						{users
							.filter(
								(x) => x.type === "agent" && 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>
			{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 />}
		</>
	);
}
