import type { GetServerSideProps } from "next";
import Head from "next/head";
import { AreaRiservataLayout } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { Status500 } from "~/components/status-page";
import { OrdiniTable } from "~/components/tables/orders-table";
import type { NextPageWithLayout } from "~/pages/_app";
import { useEnforcedSession } from "~/providers/SessionProvider";
import type { OrdiniOrdineId } from "~/schemas/public/Ordini";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { api } from "~/utils/api";

type OrdiniProps = {
	ordineId: OrdiniOrdineId | null;
};

/**
 * Pagina degli ordini: /area-riservata/ordini
 */
const Ordini: NextPageWithLayout<OrdiniProps> = ({ ordineId }: OrdiniProps) => {
	const session = useEnforcedSession();
	const { data, isLoading } = api.servizio.getOrdini.useQuery({
		userId: session.user.id,
	});

	if (isLoading) return <LoadingPage />;
	if (!data) return <Status500 />;
	return (
		<>
			<Head>
				<title>Ordini - Infoalloggi.it</title>
			</Head>
			<main className="mx-1 mt-2 flex flex-1 flex-col items-start gap-4 p-2 md:gap-6">
				<div className="grid w-full auto-rows-max items-start gap-2 md:gap-4">
					<div className="overflow-auto border-none">
						<h3 className="font-bold text-2xl">Ordini</h3>

						<div className="w-full py-4">
							<OrdiniTable
								data={data}
								filter={ordineId}
								isAdmin={false}
								userId={session.user.id}
							/>
						</div>
					</div>
				</div>
			</main>
		</>
	);
};
export default Ordini;

export const getServerSideProps = (async (context) => {
	const access_token = context.req.cookies.access_token;
	const ordineId = context.query?.ordineId;
	if (ordineId && typeof ordineId !== "string") {
		return {
			notFound: true,
		};
	}

	const helpers = await TrpcAuthedFetchingIstance({ access_token });
	if (helpers) {
		await helpers.trpc.servizio.getOrdini.prefetch({});
		return {
			props: {
				ordineId: ordineId ? (ordineId as OrdiniOrdineId) : null,
				trpcState: helpers.trpc.dehydrate(),
			},
		};
	}
	return {
		props: {},
	};
}) satisfies GetServerSideProps;

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