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

const Ordini: NextPageWithLayout = () => {
	const { t } = useTranslation();
	const { data, isLoading } = api.servizio.getOrdini.useQuery({});

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

	return (
		<>
			<Head>
				<title>{t.heads.area_riservata_titolo}</title>
				<meta content={t.heads.area_riservata_description} name="description" />
			</Head>
			<div className="mx-1 flex-1 overflow-auto">
				<div className="mx-auto pt-4">
					<div className="mx-3 items-start justify-between md:flex">
						<div className="flex max-w-lg items-center gap-3">
							<h3 className="font-bold text-2xl">Ordini</h3>
						</div>
					</div>

					<OrdiniTable data={data} isAdmin />
				</div>
			</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>;
};
