import type { GetServerSideProps } from "next";
import { UserDashboardFaq } from "~/components/area-riservata/dashboard";
import { AreaRiservataLayout } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { Rinnovo } from "~/components/servizio/rinnovo";
import { Status500 } from "~/components/status-page";
import { redirectTo500 } from "~/lib/utils";
import type { NextPageWithLayout } from "~/pages/_app";
import { RinnovoProvider } from "~/providers/RinnovoProvider";
import { useEnforcedSession } from "~/providers/SessionProvider";
import type { RinnoviId } from "~/schemas/public/Rinnovi";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { zRinnovoId } from "~/server/utils/zod_types";
import { api } from "~/utils/api";

type RinnovoPageProps = {
	rinnovoId: RinnoviId;
};

/**
 * Pagina del rinnovo: /area-riservata/rinnovo/[rinnovoId]
 */
const RinnovoPage: NextPageWithLayout<RinnovoPageProps> = ({
	rinnovoId,
}: RinnovoPageProps) => {
	const { user } = useEnforcedSession();
	const { data, isLoading } = api.servizio.getRinnovo.useQuery({
		rinnovoId,
	});
	if (isLoading) {
		return <LoadingPage />;
	}
	if (!data) {
		return <Status500 />;
	}
	return (
		<div className="flex w-full flex-1 flex-col items-start justify-center gap-3 overflow-auto p-2 md:gap-6">
			<div className="flex w-full flex-1 grow flex-col space-y-5">
				<RinnovoProvider
					isAdmin={false}
					rinnovo={data}
					rinnovoId={rinnovoId}
					userId={user.id}
				>
					<Rinnovo />
				</RinnovoProvider>
			</div>
			<div className="mx-auto">
				<UserDashboardFaq />
			</div>
		</div>
	);
};
export default RinnovoPage;

export const getServerSideProps = (async (context) => {
	const rinnovo_id = context.params?.rinnovoId;

	if (typeof rinnovo_id !== "string") {
		console.error("Error: rinnovoId is not a string");
		return redirectTo500;
	}

	const parsedRinnovoId = zRinnovoId.safeParse(rinnovo_id);
	if (!parsedRinnovoId.success) {
		console.error("Error parsing rinnovoId", parsedRinnovoId.error);
		return redirectTo500;
	}
	const rinnovoId = parsedRinnovoId.data;

	const access_token = context.req.cookies.access_token;

	const helper = await TrpcAuthedFetchingIstance({ access_token });
	if (helper) {
		await helper.trpc.servizio.getRinnovo.prefetch({
			rinnovoId,
		});

		return {
			props: {
				rinnovoId,
				trpcState: helper.trpc.dehydrate(),
			},
		};
	}

	return redirectTo500;
}) satisfies GetServerSideProps<RinnovoPageProps>;

RinnovoPage.getLayout = function getLayout(page) {
	return <AreaRiservataLayout>{page}</AreaRiservataLayout>;
};
