import type { GetServerSideProps } from "next";
import { AreaRiservataLayout } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { Status500 } from "~/components/status-page";
import { FormNewServizioAcquisto } from "~/forms/FormNewServizioAcquisto";
import type { NextPageWithLayout } from "~/pages/_app";
import { useTranslation } from "~/providers/I18nProvider";
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 OnboardServizioProps = {
	servizioId: ServizioServizioId;
};

const OnboardServizio: NextPageWithLayout<OnboardServizioProps> = ({
	servizioId,
}: OnboardServizioProps) => {
	const { data, isLoading } = api.servizio.getAcquistoData.useQuery({
		servizioId: servizioId,
	});
	const { locale } = useTranslation();
	if (isLoading) {
		return <LoadingPage />;
	}
	if (!data) {
		return <Status500 />;
	}
	return (
		<div className="mx-auto w-full max-w-6xl grow space-y-6 p-2 sm:px-8 sm:py-6">
			<div className="flex justify-center">
				<h3 className="font-bold text-3xl text-primary">
					{locale === "it" ? "Dettagli del servizio" : "Service Details"}
				</h3>
			</div>

			<FormNewServizioAcquisto initialData={data} userId={data.userData.id} />
		</div>
	);
};

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

export default OnboardServizio;

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

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

	const parsed = zServizioId.safeParse(id);
	if (!parsed.success) {
		console.error("Error parsing servizioId", 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.servizio.getAcquistoData.prefetch({
			servizioId: parsed.data,
		});
		const servizio = await helper.trpc.servizio.getServizio.fetch({
			servizioId: parsed.data,
		});

		if (
			!servizio ||
			servizio.isOkAcconto ||
			servizio.isInterrotto ||
			servizio.decorrenza !== null
		) {
			return {
				redirect: {
					destination: "/area-riservata/dashboard",
					permanent: false,
				},
			};
		}
		return {
			props: {
				servizioId: parsed.data,
				trpcState: helper.trpc.dehydrate(),
			},
		};
	}

	return {
		redirect: {
			destination: `/servizio/pre-onboard/${parsed.data}`,
			permanent: false,
		},
	};
}) satisfies GetServerSideProps<OnboardServizioProps>;
