import type { GetServerSideProps } from "next";
import CheckoutForm from "~/components/checkout";
import { AreaRiservataLayout } from "~/components/Layout";
import stripe from "~/lib/stripe";
import type { NextPageWithLayout } from "~/pages/_app";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { zPagamentoId } from "~/server/utils/zod_types";

type PagamentoPageProps = {
	clientSecret: string | null;
	titolo: string;
	prezzo: number;
	descrizione: string;
};

const PagamentoPage: NextPageWithLayout<PagamentoPageProps> = ({
	clientSecret,
	titolo,
	prezzo,
	descrizione,
}: PagamentoPageProps) => {
	if (!clientSecret) {
		return <div>Errore nella creazione del pagamento. Riprova più tardi.</div>;
	}
	return (
		<div className="mx-auto my-5 w-full max-w-lg space-y-8" id="checkout">
			<CheckoutForm
				clientSecret={clientSecret}
				descrizione={descrizione}
				prezzo={prezzo}
				titolo={titolo}
			/>
		</div>
	);
};

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

export default PagamentoPage;

export const getServerSideProps = (async (context) => {
	const id = context.params?.paymentId;
	if (typeof id !== "string") {
		console.error("Error: paymentId is not a string");
		return {
			redirect: {
				destination: "/500",
				permanent: false,
			},
		};
	}

	const parsed = zPagamentoId.safeParse(id);
	if (!parsed.success) {
		console.error("Error parsing paymentId", 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 paymentData =
			await helper.trpc.pagamenti.getPagamentoDataForCheckout.fetch({
				paymentId: parsed.data,
			});

		const { client_secret: clientSecret } = await stripe.paymentIntents.create({
			amount: paymentData.amount_cent,

			automatic_payment_methods: {
				enabled: true,
			},
			currency: "eur",
			description: paymentData.nome_it,
			metadata: {
				paymentId: paymentData.id,
				servizioId: paymentData.servizio_id,
				userId: paymentData.userid,
			},
			receipt_email: paymentData.email,
		});

		if (!clientSecret) {
			return {
				redirect: {
					destination: "/500",
					permanent: false,
				},
			};
		}

		return {
			props: {
				clientSecret,
				titolo: paymentData.nome_it,
				prezzo: paymentData.amount_cent,
				descrizione: paymentData.desc_it,
			},
		};
	}
	return {
		redirect: {
			destination: "/500",
			permanent: false,
		},
	};
}) satisfies GetServerSideProps<PagamentoPageProps>;
