/* eslint-disable @next/next/no-img-element */
import CardList from "@/components/High/CardList";
import { useEntityPermission } from "@/hooks/useEntityPermissions";
import { EntityWithRoles, Role} from "@/interfaces/entity";
import { User} from "@/interfaces/user";
import {sessionOptions} from "@/lib/session";
import { redirect, serialize } from "@/utils";
import { requestUser } from "@/utils/api";
import {getEntityWithRoles} from "@/utils/entities.be";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import { doesEntityAllow} from "@/utils/permissions";
import {getEntityUsers} from "@/utils/users.be";
import axios from "axios";
import clsx from "clsx";
import {withIronSessionSsr} from "iron-session/next";
import Head from "next/head";
import Link from "next/link";
import {useRouter} from "next/router";
import {Divider} from "primereact/divider";
import {
	BsChevronLeft,
	BsPlus,
} from "react-icons/bs";
import {toast, ToastContainer} from "react-toastify";

export const getServerSideProps = withIronSessionSsr(async ({req, res, params}) => {
	const user = await requestUser(req, res)
	if (!user) return redirect("/login")

	if (shouldRedirectHome(user)) return redirect("/")

	const {id} = params as {id: string};

	const entity = await getEntityWithRoles(id);
	if (!entity) return redirect("/entities")
	if (!doesEntityAllow(user, entity, "view_entity_roles")) return redirect(`/entities/${id}`)

	const users = await getEntityUsers(id);

	return {
		props: serialize({
			user,
			entity,
			roles: entity.roles,
			users,
		}),
	};
}, sessionOptions);

interface Props {
	user: User;
	entity: EntityWithRoles;
	roles: Role[];
	users: User[];
}

export default function Home({user, entity, roles, users}: Props) {
	const router = useRouter();

	const canCreateRole = useEntityPermission(user, entity, "create_entity_role")

	const createRole = () => {
		if (!canCreateRole) return
		const label = prompt("What is the name of this new role?")
		if (!label) return

		axios.post<Role>('/api/roles', {label, permissions: [], entityID: entity.id})
			.then((result) => {
				toast.success(`'${label}' role created successfully!`)
				router.push(`/entities/${entity.id}/roles/${result.data.id}`)
			})
			.catch(() => {
				toast.error("Something went wrong!")
			})
	}

	const firstCard = () => (
		<button
			onClick={createRole}
			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 Role</span>
		</button>
	);

	const renderCard = (role: Role) => {
		const usersWithRole = users.filter((x) => x.entities.map((x) => x.role).includes(role.id));

		return (
			<Link
				href={`/entities/${entity.id}/roles/${role.id}`}
				key={role.id}
				className={clsx(
					"p-4 pr-6 h-fit relative border rounded-xl flex flex-col gap-3  text-left cursor-pointer",
					"hover:border-mti-purple transition ease-in-out duration-300",
				)}>
				<div className="flex flex-col">
					<span className="font-semibold">{role.label}</span>
					<span className="opacity-80 text-sm">{usersWithRole.length} members</span>
				</div>

				<b>{role.permissions.length} Permissions</b>
			</Link>
		);
	};

	return (
		<>
			<Head>
				<title>{entity.label} | 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 />
			<>
				<section className="flex flex-col gap-0">
					<div className="flex flex-col gap-3">
						<div className="flex items-end justify-between">
							<div className="flex items-center gap-2">
								<Link
									href={`/entities/${entity.id}`}
									className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
									<BsChevronLeft />
								</Link>
								<h2 className="font-bold text-2xl">{entity.label}</h2>
							</div>
						</div>
					</div>
					<Divider />
					<span className="font-semibold text-xl mb-4">Roles</span>

					<CardList list={roles} searchFields={[["label"]]} renderCard={renderCard} firstCard={canCreateRole ? firstCard : undefined} />
				</section>
			</>
		</>
	);
}
