import type { GetServerSideProps } from "next";
import Head from "next/head";
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 { OrdiniOrdineId } from "~/schemas/public/Ordini";
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;
	ordineId: OrdiniOrdineId | null;
};

/**
 * Pagina di visualizzazione ordini per admin: /area-riservata/admin/user-view/ordini/[userId]
 */
const OrdiniUser: NextPageWithLayout<OrdiniUserProps> = ({
	userId,
	ordineId,
}: OrdiniUserProps) => {
	const { data, isLoading } = api.servizio.getOrdini.useQuery({
		userId,
	});

	if (isLoading) return <LoadingPage />;
	if (!data) return <Status500 />;
	return (
		<>
			<Head>
				<title>Ordini - Infoalloggi.it</title>
			</Head>
			<main className="flex flex-1 flex-col items-start gap-4">
				<div className="flex w-full flex-wrap items-center justify-between gap-2">
					<h3 className="flex items-center gap-2 font-bold text-2xl">Ordini</h3>
				</div>
				<OrdiniTable data={data} filter={ordineId} 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 ordineId = context.query?.ordineId;
	if (ordineId && typeof ordineId !== "string") {
		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: {
				ordineId: ordineId ? (ordineId as OrdiniOrdineId) : null,
				userId: parsed.data,
				trpcState: helpers.trpc.dehydrate(),
			},
		};
	}
	return {
		notFound: true,
	};
}) satisfies GetServerSideProps<OrdiniUserProps>;

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