import type { GetServerSideProps } from "next";
import Link from "next/link";
import { AllegatoIframe } from "~/components/allegato-iframe";
import { AreaRiservataLayout } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { getStorageUrl } from "~/lib/storage_utils";
import { redirectTo500 } from "~/lib/utils";
import type { NextPageWithLayout } from "~/pages/_app";
import { useTranslation } from "~/providers/I18nProvider";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { zAnnuncioId, zServizioId } from "~/server/utils/zod_types";
import { api } from "~/utils/api";

type ContrattoViewerProps = {
	storageId: string;
};
/**
 * Pagina di visualizzazione del contratto di registrazione: /servizio/contratto-registrazione/[servizioId]/[annuncioId]
 */
const ContrattoViewer: NextPageWithLayout<ContrattoViewerProps> = ({
	storageId,
}: ContrattoViewerProps) => {
	const { data: fileInfos, isLoading } = api.storage.getFileInfos.useQuery({
		storageId,
	});
	const { t } = useTranslation();
	if (isLoading) return <LoadingPage />;
	if (!fileInfos) return <p>{t.file_section.error}</p>;
	return (
		<div className="mx-2 flex flex-1 overflow-auto">
			<div className="mx-auto flex grow sm:grow-0">
				<div className="flex flex-col items-center space-y-4 py-4">
					<h1 className="font-bold text-xl">
						{t.servizio.contratto_view.ricevuta}
					</h1>
					<p className="text-center">
						{t.servizio.contratto_view.ricevuta_cta}
					</p>
					<AllegatoIframe
						allegato={fileInfos}
						className="h-full max-h-[70vh]"
					/>

					<Link
						className="underline underline-offset-1 after:content-['_↗']"
						href={getStorageUrl({
							storageId: fileInfos.id,
							params: { mode: "download" },
						})}
					>
						{t.file_section.download}
					</Link>
				</div>
			</div>
		</div>
	);
};

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

export default ContrattoViewer;

export const getServerSideProps = (async (context) => {
	const slug = context.params?.slug;
	if (!slug || slug.length !== 2) {
		return {
			notFound: true,
		};
	}
	const [servizioId, annuncioId] = slug;
	if (!servizioId || !annuncioId) {
		return {
			notFound: true,
		};
	}

	const parsedServizioId = zServizioId.safeParse(servizioId);
	const parsedAnnuncioId = zAnnuncioId.safeParse(parseInt(annuncioId));

	if (!parsedServizioId.success || !parsedAnnuncioId.success) {
		return {
			notFound: true,
		};
	}

	const access_token = context.req.cookies.access_token;

	const helper = await TrpcAuthedFetchingIstance({ access_token });
	if (helper) {
		const storageId = await helper.trpc.servizio.getServizioRegistrazione.fetch(
			{
				annuncioId: parsedAnnuncioId.data,
				servizioId: parsedServizioId.data,
			},
		);
		if (!storageId) {
			return redirectTo500;
		}

		await helper.trpc.storage.getFileInfos.prefetch({
			storageId,
		});

		return {
			props: {
				storageId,
				trpcState: helper.trpc.dehydrate(),
			},
		};
	}
	return redirectTo500;
}) satisfies GetServerSideProps<ContrattoViewerProps>;
