import type { GetServerSideProps } from "next";
import { AreaRiservataLayout } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { Servizio } from "~/components/servizio/servizio";
import { Status500 } from "~/components/status-page";
import type { NextPageWithLayout } from "~/pages/_app";
import { useTranslation } from "~/providers/I18nProvider";
import { useEnforcedSession } from "~/providers/SessionProvider";
import type { ServizioServizioId } from "~/schemas/public/Servizio";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { zServizioId } from "~/server/utils/zod_types";
import { api } from "~/utils/api";

type ServizioPageProps = {
	servizioId: ServizioServizioId;
};
const ServizioPage: NextPageWithLayout<ServizioPageProps> = ({
	servizioId,
}: ServizioPageProps) => {
	const { user } = useEnforcedSession();
	const { t } = useTranslation();
	const { data, isLoading } = api.servizio.getServizioData.useQuery({
		servizioId,
	});

	if (isLoading) {
		return <LoadingPage />;
	}
	if (!data) {
		return <Status500 />;
	}
	return (
		<div className="mx-auto w-full max-w-8xl grow space-y-4 p-4">
			<div className="flex justify-between">
				<h3 className="font-bold text-2xl">{t.servizio.dettaglio_servizio}</h3>
			</div>
			<Servizio
				isAdmin={false}
				key={data.servizio_id}
				servizio={data}
				userId={user.id}
			/>
		</div>
	);
};
export default ServizioPage;

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

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

	const parsedServizioId = zServizioId.safeParse(servizio_id);
	if (!parsedServizioId.success) {
		console.error("Error parsing servizioId", parsedServizioId.error);
		return {
			redirect: {
				destination: "/500",
				permanent: false,
			},
		};
	}
	const servizioId = parsedServizioId.data;

	const access_token = context.req.cookies.access_token;

	const helper = await TrpcAuthedFetchingIstance({ access_token });
	if (helper) {
		await helper.trpc.servizio.getServizio.prefetch({
			servizioId,
		});

		return {
			props: {
				servizioId,
				trpcState: helper.trpc.dehydrate(),
			},
		};
	}

	return {
		redirect: {
			destination: `/area-riservata/admin/utenti`,
			permanent: false,
		},
	};
}) satisfies GetServerSideProps<ServizioPageProps>;

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