import type { GetServerSideProps } from "next";
import { AreaRiservataLayoutUserView } 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 type { RinnoviId } from "~/schemas/public/Rinnovi";
import type { UsersId } from "~/schemas/public/Users";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { zRinnovoId, zUserId } from "~/server/utils/zod_types";
import { api } from "~/utils/api";

type RinnovoUserProps = {
	rinnovoId: RinnoviId;
	userId: UsersId;
};
/**
 * Pagina di visualizzazione rinnovo per admin: /area-riservata/admin/user-view/rinnovo/[userId]/[rinnovoId]
 */
const RinnovoUser: NextPageWithLayout<RinnovoUserProps> = ({
	rinnovoId,
	userId,
}: RinnovoUserProps) => {
	const { data, isLoading } = api.servizio.getRinnovo.useQuery({
		rinnovoId,
	});
	if (isLoading) {
		return <LoadingPage />;
	}
	if (!data) {
		return <Status500 />;
	}
	return (
		<div className="mx-auto max-w-8xl grow space-y-4">
			<RinnovoProvider
				isAdmin={true}
				rinnovo={data}
				rinnovoId={rinnovoId}
				userId={userId}
			>
				<Rinnovo />
			</RinnovoProvider>
		</div>
	);
};
export default RinnovoUser;

export const getServerSideProps = (async (context) => {
	const user_id = context.params?.slug?.[0];
	const rinnovo_id = context.params?.slug?.[1];

	if (typeof rinnovo_id !== "string" || typeof user_id !== "string") {
		console.error("Error: rinnovoId or userId is not a string");
		return redirectTo500
	}
	const parsedUserId = zUserId.safeParse(user_id);
	if (!parsedUserId.success) {
		console.error("Error parsing userId", parsedUserId.error);
		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 userId = parsedUserId.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(),
				userId,
			},
		};
	}

	return redirectTo500
}) satisfies GetServerSideProps<RinnovoUserProps>;

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