import type { GetServerSideProps } from "next";
import { AreaRiservataLayout } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { Status500 } from "~/components/status-page";
import { redirectTo500 } from "~/lib/utils";
import type { NextPageWithLayout } from "~/pages/_app";
import type { TestiEStringheStingaId } from "~/schemas/public/TestiEStringhe";
import { generateSSGHelper } from "~/server/utils/ssgHelper";
import { zTestiEStringheStingaId } from "~/server/utils/zod_types";
import { api } from "~/utils/api";

type CondizioniProps = {
	stringaId: TestiEStringheStingaId;
};
/**
 * Pagina condizioni: /servizio/condizioni/[stringaId]
 */
const CondizioniPage: NextPageWithLayout<CondizioniProps> = ({
	stringaId,
}: CondizioniProps) => {
	const { data, isLoading } = api.strings.getStringa.useQuery({
		stringaId,
	});

	if (isLoading) {
		return <LoadingPage />;
	}
	if (!data) {
		return <Status500 />;
	}
	return (
		<div className="w-full grow space-y-4 p-4 text-foreground sm:p-6">
			{data && (
				<div
					className="prose dark:prose-invert mx-auto max-w-5xl"
					dangerouslySetInnerHTML={{ __html: data.stringa_value || "" }}
				/>
			)}
		</div>
	);
};

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

export default CondizioniPage;

export const getServerSideProps = (async (context) => {
	const id = context.params?.stringaId;
	const raw = context.query?.raw;
	if (typeof id !== "string") {
		console.error("Error: stringaId is not a string");
		return redirectTo500;
	}

	const parsed = zTestiEStringheStingaId.safeParse(id);
	if (!parsed.success) {
		console.error("Error parsing paymentId", parsed.error);
		return redirectTo500;
	}

	const helper = generateSSGHelper();
	if (helper) {
		await helper.strings.getStringa.prefetch({
			stringaId: parsed.data,
		});

		return {
			props: {
				raw: raw === "true",
				stringaId: parsed.data,
				trpcState: helper.dehydrate(),
			},
		};
	}
	return redirectTo500;
}) satisfies GetServerSideProps<CondizioniProps>;
