/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import {Permission} from "@/interfaces/permissions";
import {getPermissionDocs} from "@/utils/permissions.be";
import {User} from "@/interfaces/user";
import Layout from "@/components/High/Layout";
import PermissionList from "@/components/PermissionList";

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

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

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

	// Fetch data from external API
	const permissions: Permission[] = await getPermissionDocs();
	const filteredPermissions = permissions.filter((p) => {
		const permissionType = p.type.toString().toLowerCase();

		if (user.type === "corporate") return !permissionType.includes("corporate") && !permissionType.includes("admin");
		if (user.type === "mastercorporate") return !permissionType.includes("mastercorporate") && !permissionType.includes("admin");

		return true;
	});

	// const res = await fetch("api/permissions");
	// const permissions: Permission[] = await res.json();
	// Pass data to the page via props
	return {
		props: {
			// permissions: permissions.map((p) => ({ id: p.id, type: p.type })),
			permissions: filteredPermissions.map((p) => {
				const {users, ...rest} = p;
				return rest;
			}),
			user: req.session.user,
		},
	};
}, sessionOptions);

interface Props {
	permissions: Permission[];
	user: User;
}

export default function Page(props: Props) {
	const {permissions, user} = props;

	return (
		<>
			<Head>
				<title>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>
			<Layout user={user} className="gap-6">
				<h1 className="text-2xl font-semibold">Permissions</h1>
				<div className="flex gap-3 flex-wrap overflow-y-scroll scrollbar-hide h-[80vh] rounded-xl">
					<PermissionList permissions={permissions} />
				</div>
			</Layout>
		</>
	);
}
