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 { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { api } from "~/utils/api";

/**
 * Pagina di gestione ordini per admin: /area-riservata/admin/ordini
 */
const Ordini: NextPageWithLayout = () => {
	const { data, isLoading } = api.servizio.getOrdini.useQuery({});

	if (isLoading) return <LoadingPage />;
	if (!data) return <Status500 />;

	return (
		<>
			<Head>
				<title>Ordini - Infoalloggi.it</title>
			</Head>

			<div className="mx-3 flex flex-1 flex-col gap-4 overflow-auto pt-5">
				<div className="items-start justify-between md:flex">
					<div className="mx-1 flex items-center">
						<h3 className="font-bold text-2xl">Ordini</h3>
					</div>
				</div>
				<OrdiniTable data={data} filter={null} isAdmin />
			</div>
		</>
	);
};
export default Ordini;

export const getServerSideProps = (async (context) => {
	const access_token = context.req.cookies.access_token;

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

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