import type { GetServerSideProps } from "next";
import { AreaRiservataLayoutUserView } from "~/components/Layout";
import { LoadingPage } from "~/components/loading";
import { NewServizioModal } from "~/components/servizio/parametri_ricerca";
import { NewRinnovoModal } from "~/components/servizio/rinnovo";
import { ServizioList } from "~/components/servizio/servizio";
import { AnnunciRichiesti } from "~/components/servizio/servizio_annunci_accordions";
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 RicercaUserProps = {
	userId: UsersId;
};

/**
 * Pagina di visualizzazione ricerca per admin: /area-riservata/admin/user-view/ricerca/[userId]
 */
const RicercaUser: NextPageWithLayout<RicercaUserProps> = ({
	userId,
}: RicercaUserProps) => {
	const { data, isLoading } = api.servizio.getAllServiziData.useQuery({
		userId,
	});
	if (isLoading) return <LoadingPage />;

	return (
		<div className="flex flex-col gap-5">
			<div className="flex w-full flex-wrap items-center justify-between gap-2">
				<h3 className="font-semibold text-xl">Servizi cliente</h3>
				<div className="flex items-center gap-2">
					<NewServizioModal userId={userId} />
					<NewRinnovoModal userId={userId} />
				</div>
			</div>
			<AnnunciRichiesti userId={userId} />
			<ServizioList data={data || []} isAdmin userId={userId} />
		</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.getAllServiziData.prefetch({
			userId: parsed.data,
		});
		return {
			props: {
				userId: parsed.data,
				trpcState: helpers.trpc.dehydrate(),
			},
		};
	}
	return {
		notFound: true,
	};
}) satisfies GetServerSideProps<RicercaUserProps>;

export default RicercaUser;
