/* 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, BsPersonFill, BsBank, BsCurrencyDollar} from "react-icons/bs";
import UserCard from "@/components/UserCard";
import useGroups from "@/hooks/useGroups";

import IconCard from "./IconCard";
import usePaymentStatusUsers from "@/hooks/usePaymentStatusUsers";

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 {data: stats} = useFilterRecordsByUser<Stat[]>();
	const {users, reload} = useUsers();
	const {pending, done} = usePaymentStatusUsers();

	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, allowClick = true}: {displayUser: User; allowClick?: boolean}) => (
		<div
			onClick={() => allowClick && 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 (
			<UserList
				user={user}
				filters={[referredCorporateFilter]}
				renderHeader={(total) => (
					<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 ({total})</h2>
					</div>
				)}
			/>
		);
	};

	const InactiveReferredCorporateList = () => {
		return (
			<UserList
				user={user}
				filters={[inactiveReferredCorporateFilter]}
				renderHeader={(total) => (
					<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 ({total})</h2>
					</div>
				)}
			/>
		);
	};

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

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

	const DefaultDashboard = () => (
		<>
			<section className="flex flex-wrap gap-2 items-center -lg:justify-center lg:gap-4 text-center">
				<IconCard
					onClick={() => setPage("referredCorporate")}
					Icon={BsBank}
					label="Referred Corporate"
					value={users.filter(referredCorporateFilter).length}
					color="purple"
				/>
				<IconCard
					onClick={() => setPage("inactiveReferredCorporate")}
					Icon={BsBank}
					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"
				/>
				<IconCard onClick={() => setPage("paymentdone")} Icon={BsCurrencyDollar} label="Payment Done" value={done.length} color="purple" />
				<IconCard
					onClick={() => setPage("paymentpending")}
					Icon={BsCurrencyDollar}
					label="Pending Payment"
					value={pending.length}
					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 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} displayUser={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} displayUser={x} allowClick={false} />
							))}
					</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} displayUser={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 === "paymentdone" && <CorporatePaidStatusList paid={true} />}
			{page === "paymentpending" && <CorporatePaidStatusList paid={false} />}
			{page === "" && <DefaultDashboard />}
		</>
	);
}
