import { loadStripe } from "@stripe/stripe-js";
import type { GetServerSideProps } from "next";
import { AcquistoProcessing } from "~/components/acquisto_processing";
import { AreaRiservataLayout } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { Status500 } from "~/components/status-page";
import { env } from "~/env";
import type { NextPageWithLayout } from "~/pages/_app";
import { useTranslation } from "~/providers/I18nProvider";
import type { OrdiniOrdineId } from "~/schemas/public/Ordini";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { zOrdineId } from "~/server/utils/zod_types";
import { api } from "~/utils/api";

type ServizioPurchaseProps = {
	ordineId: OrdiniOrdineId;
};

const ServicePurchasePage: NextPageWithLayout<ServizioPurchaseProps> = ({
	ordineId,
}: ServizioPurchaseProps) => {
	const { data, isLoading } = api.servizio.getServizioPaymentData.useQuery({
		ordineId,
	});
	const { t } = useTranslation();
	const stripePromise = loadStripe(env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY);

	if (isLoading) {
		return <LoadingPage />;
	}
	if (!data) {
		return <Status500 />;
	}
	return (
		<div className="mx-auto w-full max-w-6xl grow space-y-4 p-2 sm:px-8 sm:py-4">
			<div className="flex justify-between">
				<h3 className="font-bold text-3xl text-primary">
					{t.acquisto.pagamento}
				</h3>
			</div>
			<AcquistoProcessing
				packId={data.ordine.packid}
				paymentId={data.payment.id}
				stripePromise={stripePromise}
			/>
		</div>
	);
};

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

export default ServicePurchasePage;

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

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

	const parsed = zOrdineId.safeParse(id);
	if (!parsed.success) {
		console.error("Error parsing ordineId", parsed.error);
		return {
			redirect: {
				destination: "/500",
				permanent: false,
			},
		};
	}

	const access_token = context.req.cookies.access_token;

	const helper = await TrpcAuthedFetchingIstance({ access_token });
	if (helper) {
		const isAwaitingPayment =
			await helper.trpc.servizio.isOrdineAwaitingPayment.fetch({
				ordineId: parsed.data,
			});
		if (!isAwaitingPayment) {
			return {
				redirect: {
					destination: "/area-riservata/dashboard",
					permanent: false,
				},
			};
		}

		await helper.trpc.servizio.getServizioPaymentData.prefetch({
			ordineId: parsed.data,
		});

		return {
			props: {
				ordineId: parsed.data,
				trpcState: helper.trpc.dehydrate(),
			},
		};
	}
	return {
		redirect: {
			destination: "/500",
			permanent: false,
		},
	};
}) satisfies GetServerSideProps<ServizioPurchaseProps>;
