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 { useEnforcedSession } from "~/providers/SessionProvider";
import type { UsersId } from "~/schemas/public/Users";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { api } from "~/utils/api";

const Ordini: NextPageWithLayout = () => {
	const { t } = useTranslation();
	const session = useEnforcedSession();
	return (
		<>
			<Head>
				<title>{t.heads.area_riservata_titolo}</title>
				<meta content={t.heads.area_riservata_description} name="description" />
			</Head>
			<SessionWrapper userId={session.user.id} />
		</>
	);
};
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;

const SessionWrapper = ({ userId }: { userId: UsersId }) => {
	const { data, isLoading } = api.servizio.getOrdini.useQuery({
		userId,
	});

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

	return (
		<main className="mx-1 mt-2 flex flex-1 flex-col items-start gap-4 p-2 md:gap-8">
			<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} isAdmin={false} userId={userId} />
					</div>
				</div>
			</div>
		</main>
	);
};

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