/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import { withIronSessionSsr } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import useUser from "@/hooks/useUser";
import PaymentDue from "./(status)/PaymentDue";
import { useRouter } from "next/router";
import { requestUser } from "@/utils/api";
import { mapBy, redirect, serialize } from "@/utils";
import { getEntitiesWithRoles } from "@/utils/entities.be";
import { isAdmin } from "@/utils/users";
import { EntityWithRoles } from "@/interfaces/entity";
import { User } from "@/interfaces/user";
import { Discount, Package } from "@/interfaces/paypal";

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

	const entityIDs = mapBy(user.entities, 'id')
	const entities = await getEntitiesWithRoles(isAdmin(user) ? undefined : entityIDs);

	return {
		props: serialize({ user, entities, discounts: [] as Discount[], packages: [] as Package[] }),
	};
}, sessionOptions);

interface Props {
	user: User,
	entities: EntityWithRoles[]
	discounts: Discount[]
	packages: Package[]
}

export default function Home(props: Props) {
	const router = useRouter();

	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>

			<PaymentDue {...props} reload={router.reload} />
		</>
	);
}
