import type { GetServerSideProps } from "next";
import Head from "next/head";
import { AreaRiservataLayout } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { SchedaAnnuncioStampabile } from "~/components/schedaAnnuncioStampabile";
import { Status500 } from "~/components/status-page";
import type { NextPageWithLayout } from "~/pages/_app";
import type { AnnunciId } from "~/schemas/public/Annunci";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { zAnnuncioId } from "~/server/utils/zod_types";
import { api } from "~/utils/api";

type PageProps = {
	id: AnnunciId;
};

const SchedaAnnuncioPage: NextPageWithLayout<PageProps> = ({
	id,
}: PageProps) => {
	const { data, isLoading } = api.annunci.getAnnuncioById_rawImgUrls.useQuery({
		id,
	});

	if (isLoading) {
		return <LoadingPage />;
	}
	if (!data) {
		return <Status500 />;
	}
	return (
		<>
			<Head>
				<title>Scheda Annuncio {data.codice}</title>
			</Head>
			<div className="mx-auto w-full p-4">
				<SchedaAnnuncioStampabile data={data} />
			</div>
		</>
	);
};

SchedaAnnuncioPage.getLayout = function getLayout(page) {
	return (
		<AreaRiservataLayout noFooter noSidebar>
			{page}
		</AreaRiservataLayout>
	);
};

export default SchedaAnnuncioPage;

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

	if (typeof id !== "string") {
		console.error("Error: id is not a string");
		return {
			redirect: {
				destination: "/500",
				permanent: false,
			},
		};
	}

	const parsed = zAnnuncioId.safeParse(parseInt(id));
	if (!parsed.success) {
		console.error("Error parsing ordineId", parsed.error);
		return {
			redirect: {
				destination: "/500",
				permanent: false,
			},
		};
	}

	const access_token = context.req.cookies.access_token;

	const helper = await TrpcAuthedFetchingIstance({ access_token });
	if (helper) {
		await helper.trpc.annunci.getAnnuncioById_rawImgUrls.prefetch({
			id: parsed.data,
		});

		return {
			props: {
				id: parsed.data,
				trpcState: helper.trpc.dehydrate(),
			},
		};
	}
	return {
		redirect: {
			destination: "/500",
			permanent: false,
		},
	};
}) satisfies GetServerSideProps<PageProps>;
