import type { GetServerSideProps } from "next";
import Head from "next/head";
import { AreaRiservataLayout } from "~/components/Layout";
import {
	SchedaAnnuncio,
	SchedaAnnuncioStampabile,
} from "~/components/schedaAnnuncioStampabile";
import type { NextPageWithLayout } from "~/pages/_app";
import type { AnnunciWithMedia } from "~/server/controllers/annunci.controller";
import { generateSSGHelper } from "~/server/utils/ssgHelper";
import { zAnnuncioId } from "~/server/utils/zod_types";

type PageProps = {
	raw: boolean;
	data: StringifiedAnnunciWithMedia;
};

const SchedaAnnuncioPage: NextPageWithLayout<PageProps> = ({
	raw,
	data,
}: PageProps) => {
	const annuncioData = StringifiedToAnnuncio(data);
	if (raw) {
		return <SchedaAnnuncio data={annuncioData} raw />;
	}
	return (
		<>
			<Head>
				<title>Scheda Annuncio {annuncioData.codice}</title>
			</Head>
			<div className="mx-auto w-full p-4">
				<SchedaAnnuncioStampabile data={annuncioData} />
			</div>
		</>
	);
};

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

export default SchedaAnnuncioPage;

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

	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 helper = generateSSGHelper();

	const data = await helper.annunci.getAnnuncioById_rawImgUrls.fetch({
		id: parsed.data,
	});
	if (!data) {
		return {
			notFound: true,
		};
	}

	return {
		props: {
			raw: raw === "true",
			trpcState: helper.dehydrate(),
			data : AnnuncioToStringified(data),
		},
	};
}) satisfies GetServerSideProps<PageProps>;

type StringifiedAnnunciWithMedia = Omit<
	AnnunciWithMedia,
	"creato_il" | "disponibile_da" | "media_updated_at" | "modificato_il"
> & {
	creato_il: string | undefined;
	disponibile_da: string | undefined;
	media_updated_at: string | undefined;
	modificato_il: string | undefined;
};

function AnnuncioToStringified(
	data: AnnunciWithMedia,
): StringifiedAnnunciWithMedia {
	return {
		...data,
		creato_il: data?.creato_il?.toISOString(),
		disponibile_da: data?.disponibile_da?.toISOString(),
		media_updated_at: data?.media_updated_at?.toISOString(),
		modificato_il: data?.modificato_il?.toISOString(),
	};
}

function StringifiedToAnnuncio(
	data: StringifiedAnnunciWithMedia,
): AnnunciWithMedia {
	return {
		...data,
		creato_il: data?.creato_il ? new Date(data.creato_il) : null,
		disponibile_da: data?.disponibile_da ? new Date(data.disponibile_da) : null,
		media_updated_at: data?.media_updated_at
			? new Date(data.media_updated_at)
			: null,
		modificato_il: data?.modificato_il ? new Date(data.modificato_il) : null,
	};
}
