import type { GetServerSideProps } from "next";
import { AreaRiservataLayoutUserView } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { Status500 } from "~/components/status-page";
import { FormServizioAcquisto } from "~/forms/FormServizioAcquisto";
import { redirectTo500 } from "~/lib/utils";
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;
};

/**
 * Pagina di onboarding utente per admin: /area-riservata/admin/user-view/onboard/[servizioId]
 */
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>
				<FormServizioAcquisto
					initialData={data}
					isAdmin={true}
					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 redirectTo500;
	}

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

	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 { available, userId } =
			await helper.trpc.servizio.isOnboardAvailable.fetch({
				servizioId: parsed.data,
			});

		if (!available) {
			return {
				redirect: {
					destination: `/area-riservata/dashboard`,
					permanent: false,
				},
			};
		}
		return {
			props: {
				servizioId: parsed.data,
				trpcState: helper.trpc.dehydrate(),
				userId,
			},
		};
	}

	return redirectTo500;
}) satisfies GetServerSideProps<OnboardUserProps>;

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