import type { GetServerSideProps } from "next";
import { AreaRiservataLayoutUserView } 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 type { UsersId } from "~/schemas/public/Users";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { zUserId } from "~/server/utils/zod_types";
import { api } from "~/utils/api";

type OrdiniUserProps = {
	userId: UsersId;
};

const OrdiniUser: NextPageWithLayout<OrdiniUserProps> = ({
	userId,
}: OrdiniUserProps) => {
	const { data, isLoading } = api.servizio.getOrdini.useQuery({
		userId,
	});

	if (isLoading) return <LoadingPage />;
	if (!data) return <Status500 />;
	return (
		<main className="flex flex-1 flex-col items-start gap-4">
			<div className="flex">
				<h3 className="font-bold text-2xl">Ordini</h3>
			</div>
			<OrdiniTable data={data} isAdmin userId={userId} />
		</main>
	);
};

export default OrdiniUser;
export const getServerSideProps = (async (context) => {
	const userId = context.params?.userId;
	if (typeof userId !== "string") {
		return {
			notFound: true,
		};
	}

	const parsed = zUserId.safeParse(userId);

	if (!parsed.success) {
		return {
			notFound: true,
		};
	}
	const access_token = context.req.cookies.access_token;

	const helpers = await TrpcAuthedFetchingIstance({ access_token });
	if (helpers) {
		await helpers.trpc.servizio.getOrdini.prefetch({
			userId: parsed.data,
		});
		return {
			props: {
				userId: parsed.data,
				trpcState: helpers.trpc.dehydrate(),
			},
		};
	}
	return {
		notFound: true,
	};
}) satisfies GetServerSideProps<OrdiniUserProps>;

OrdiniUser.getLayout = function getLayout(page) {
	return <AreaRiservataLayoutUserView>{page}</AreaRiservataLayoutUserView>;
};
