import type { GetServerSideProps } from "next";
import { AreaRiservataLayoutUserView } from "~/components/Layout";
import { AnnunciRichiesti } from "~/components/servizio/servizio_annunci_accordions";
import { TabRicerca } from "~/components/tables/ricerca-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";

type RicercaUserProps = {
	userId: UsersId;
};

const RicercaUser: NextPageWithLayout<RicercaUserProps> = ({
	userId,
}: RicercaUserProps) => {
	return (
		<div className="space-y-5">
			<div className="items-center justify-between md:flex">
				<div className="flex items-center gap-3">
					<h3 className="font-bold text-2xl">Le tue ricerche</h3>
				</div>
			</div>
			<div className="flex flex-col space-y-5">
				<AnnunciRichiesti userId={userId} />
				<TabRicerca isAdmin userId={userId} />
			</div>
		</div>
	);
};

RicercaUser.getLayout = (page) => {
	return <AreaRiservataLayoutUserView>{page}</AreaRiservataLayoutUserView>;
};
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.intrests.getUserInterestsAnnunci.prefetch({
			userId: parsed.data,
		});
		await helpers.trpc.servizio.getAllServizioAnnunci.prefetch({
			userId: parsed.data,
		});
		return {
			props: {
				userId: parsed.data,
				trpcState: helpers.trpc.dehydrate(),
			},
		};
	}
	return {
		notFound: true,
	};
}) satisfies GetServerSideProps<RicercaUserProps>;

export default RicercaUser;
