import type { GetServerSideProps } from "next";
import { AreaRiservataLayoutUserView } 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 { CatastoProvider } from "~/providers/CatastoProvider";
import type { ServizioServizioId } from "~/schemas/public/Servizio";
import type { UsersId } from "~/schemas/public/Users";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { zServizioId } from "~/server/utils/zod_types";
import { api } from "~/utils/api";

type OnboardUserProps = {
	servizioId: ServizioServizioId;
	userId: UsersId;
};
const OnboardUser: NextPageWithLayout<OnboardUserProps> = ({
	servizioId,
}: OnboardUserProps) => {
	const { data, isLoading } = api.servizio.getAcquistoData.useQuery({
		servizioId,
	});

	if (isLoading) {
		return <LoadingPage />;
	}
	if (!data) {
		return <Status500 />;
	}
	return (
		<div className="mx-auto max-w-8xl grow space-y-4">
			<div className="flex justify-between">
				<h3 className="font-bold text-2xl">
					Onboarding Utente (Versione Admin)
				</h3>
			</div>
			<CatastoProvider>
				<FormNewServizioAcquisto
					initialData={data}
					isAdmin
					userId={data.userData.id}
				/>
			</CatastoProvider>
		</div>
	);
};
export default OnboardUser;

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(),
				userId: servizio.user_id,
			},
		};
	}

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

OnboardUser.getLayout = function getLayout(page) {
	return <AreaRiservataLayoutUserView>{page}</AreaRiservataLayoutUserView>;
};
