import type { GetServerSideProps } from "next";
import { EmailAccordion } from "~/components/area-riservata/comunicazioni";
import { AreaRiservataLayoutUserView } from "~/components/Layout";
import type { NextPageWithLayout } from "~/pages/_app";
import { useEnforcedSession } from "~/providers/SessionProvider";
import type { UsersId } from "~/schemas/public/Users";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { zUserId } from "~/server/utils/zod_types";

type ComunicazioniUserProps = {
	userId: UsersId;
};

const ComunicazioniUser: NextPageWithLayout<ComunicazioniUserProps> = ({
	userId,
}: ComunicazioniUserProps) => {
	const { user } = useEnforcedSession();
	return (
		<main className="flex flex-1 flex-col items-start gap-4 md:gap-8">
			<div className="grid w-full auto-rows-max items-start gap-2 md:gap-4">
				<div className="overflow-auto border-none">
					<h3 className="font-bold text-2xl">Comunicazioni</h3>

					<div className="w-full py-4">
						<EmailAccordion isAdmin={user.isAdmin} userId={userId} />
					</div>
				</div>
			</div>
		</main>
	);
};

export default ComunicazioniUser;

export const getServerSideProps = (async (context) => {
	const userId = context.params?.userId;
	if (typeof userId !== "string") {
		return {
			notFound: true,
		};
	}

	const parsed = zUserId.safeParse(userId);

	if (!parsed.success) {
		return {
			notFound: true,
		};
	}
	const access_token = context.req.cookies.access_token;

	const helpers = await TrpcAuthedFetchingIstance({ access_token });
	if (helpers) {
		await helpers.trpc.comunicazioni.getEmails.prefetch({
			userId: parsed.data,
		});
		return {
			props: {
				userId: parsed.data,
				trpcState: helpers.trpc.dehydrate(),
			},
		};
	}
	return {
		notFound: true,
	};
}) satisfies GetServerSideProps<ComunicazioniUserProps>;

ComunicazioniUser.getLayout = function getLayout(page) {
	return <AreaRiservataLayoutUserView>{page}</AreaRiservataLayoutUserView>;
};
