/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {ToastContainer} from "react-toastify";
import Layout from "@/components/High/Layout";
import {GroupWithUsers, User} from "@/interfaces/user";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import {getUserName} from "@/utils/users";
import {convertToUsers, getGroupsForUser} from "@/utils/groups.be";
import {countEntityUsers, getEntityUsers, getSpecificUsers} from "@/utils/users.be";
import {checkAccess, getTypesOfUser} from "@/utils/permissions";
import Link from "next/link";
import {uniq} from "lodash";
import {BsPlus} from "react-icons/bs";
import CardList from "@/components/High/CardList";
import {getEntitiesWithRoles} from "@/utils/entities.be";
import {EntityWithRoles} from "@/interfaces/entity";
import Separator from "@/components/Low/Separator";

type EntitiesWithCount = {entity: EntityWithRoles; users: User[]; count: number};

export const getServerSideProps = withIronSessionSsr(async ({req}) => {
	const user = req.session.user;

	if (!user) {
		return {
			redirect: {
				destination: "/login",
				permanent: false,
			},
		};
	}

	if (shouldRedirectHome(user)) {
		return {
			redirect: {
				destination: "/",
				permanent: false,
			},
		};
	}

	const entities = await getEntitiesWithRoles(
		checkAccess(user, getTypesOfUser(["admin", "developer"])) ? user.entities.map((x) => x.id) : undefined,
	);

	const entitiesWithCount = await Promise.all(
		entities.map(async (e) => ({entity: e, count: await countEntityUsers(e.id), users: await getEntityUsers(e.id, 5)})),
	);

	return {
		props: {user, entities: JSON.parse(JSON.stringify(entitiesWithCount))},
	};
}, sessionOptions);

const SEARCH_FIELDS: string[][] = [["entity", "label"]];

interface Props {
	user: User;
	entities: EntitiesWithCount[];
}
export default function Home({user, entities}: Props) {
	const renderCard = ({entity, users, count}: EntitiesWithCount) => (
		<Link
			href={`/entities/${entity.id}`}
			key={entity.id}
			className="p-4 border rounded-xl flex flex-col gap-2 hover:border-mti-purple transition ease-in-out duration-300 text-left cursor-pointer">
			<span>
				<b>Entity: </b>
				{entity.label}
			</span>
			<b>Members ({count}): </b>
			<span>
				{users.map(getUserName).join(", ")}
				{count > 5 ? <span className="opacity-60"> and {count - 5} more</span> : ""}
			</span>
		</Link>
	);

	const firstCard = () => (
		<Link
			href={`/entities/create`}
			className="p-4 border hover:text-mti-purple rounded-xl flex flex-col items-center justify-center gap-0 hover:border-mti-purple transition ease-in-out duration-300 text-left cursor-pointer">
			<BsPlus size={40} />
			<span className="font-semibold">Create Entity</span>
		</Link>
	);

	return (
		<>
			<Head>
				<title>Entities | EnCoach</title>
				<meta
					name="description"
					content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
				/>
				<meta name="viewport" content="width=device-width, initial-scale=1" />
				<link rel="icon" href="/favicon.ico" />
			</Head>
			<ToastContainer />
			{user && (
				<Layout user={user} className="!gap-4">
					<section className="flex flex-col gap-4 w-full h-full">
						<div className="flex flex-col gap-4">
							<h2 className="font-bold text-2xl">Entities</h2>
							<Separator />
						</div>

						<CardList<EntitiesWithCount> list={entities} searchFields={SEARCH_FIELDS} renderCard={renderCard} firstCard={firstCard} />
					</section>
				</Layout>
			)}
		</>
	);
}
