import type { GetServerSideProps } from "next";
import { UserDashboardFaq } from "~/components/area-riservata/dashboard";
import { AreaRiservataLayout } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { Servizio } from "~/components/servizio/servizio";
import { Status500 } from "~/components/status-page";
import { redirectTo500 } from "~/lib/utils";
import type { NextPageWithLayout } from "~/pages/_app";
import { useEnforcedSession } from "~/providers/SessionProvider";
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 ServizioPageProps = {
	servizioId: ServizioServizioId;
};

/**
 * Pagina del servizio: /area-riservata/servizio/[servizioId]
 */
const ServizioPage: NextPageWithLayout<ServizioPageProps> = ({
	servizioId,
}: ServizioPageProps) => {
	const { user } = useEnforcedSession();
	const { data, isLoading } = api.servizio.getServizioData.useQuery({
		servizioId,
	});

	if (isLoading) {
		return <LoadingPage />;
	}
	if (!data) {
		return <Status500 />;
	}
	return (
		<div className="flex w-full flex-1 flex-col items-start justify-center gap-3 overflow-auto p-2 md:gap-6">
			<div className="flex w-full flex-1 grow flex-col space-y-5">
				<Servizio
					isAdmin={false}
					key={data.servizio_id}
					servizio={data}
					userId={user.id}
				/>
			</div>
			<div className="mx-auto">
				<UserDashboardFaq />
			</div>
		</div>
	);
};
export default ServizioPage;

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

	if (typeof servizio_id !== "string") {
		console.error("Error: servizioId is not a string");
		return redirectTo500;
	}

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

	const access_token = context.req.cookies.access_token;

	const helper = await TrpcAuthedFetchingIstance({ access_token });
	if (helper) {
		await helper.trpc.servizio.getServizioData.prefetch({
			servizioId,
		});

		return {
			props: {
				servizioId,
				trpcState: helper.trpc.dehydrate(),
			},
		};
	}

	return redirectTo500;
}) satisfies GetServerSideProps<ServizioPageProps>;

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