/* 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 {getSpecificUsers} from "@/utils/users.be";
import {checkAccess} 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 Separator from "@/components/Low/Separator";

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 groups = await getGroupsForUser(
		checkAccess(user, ["corporate", "mastercorporate"]) ? user.id : undefined,
		checkAccess(user, ["teacher", "student"]) ? user.id : undefined,
	);

	const users = await getSpecificUsers(uniq(groups.flatMap((g) => [...g.participants.slice(0, 5), g.admin])));
	const groupsWithUsers: GroupWithUsers[] = groups.map((g) => convertToUsers(g, users));

	return {
		props: {user, groups: JSON.parse(JSON.stringify(groupsWithUsers))},
	};
}, sessionOptions);

const SEARCH_FIELDS = [
	["name"],
	["admin", "name"],
	["admin", "email"],
	["admin", "corporateInformation", "companyInformation", "name"],
	["participants", "name"],
	["participants", "email"],
	["participants", "corporateInformation", "companyInformation", "name"],
];

interface Props {
	user: User;
	groups: GroupWithUsers[];
}
export default function Home({user, groups}: Props) {
	const renderCard = (group: GroupWithUsers) => (
		<Link
			href={`/groups/${group.id}`}
			key={group.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>Group: </b>
				{group.name}
			</span>
			<span>
				<b>Admin: </b>
				{getUserName(group.admin)}
			</span>
			<b>Participants ({group.participants.length}): </b>
			<span>
				{group.participants.slice(0, 5).map(getUserName).join(", ")}
				{group.participants.length > 5 ? <span className="opacity-60"> and {group.participants.length - 5} more</span> : ""}
			</span>
		</Link>
	);

	const firstCard = () => (
		<Link
			href={`/groups/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 Group</span>
		</Link>
	);

	return (
		<>
			<Head>
				<title>Groups | 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">Classrooms</h2>
							<Separator />
						</div>

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