import { MoreVertical, Trash2 } from "lucide-react";
import type { GetServerSideProps } from "next";
import toast from "react-hot-toast";
import { EmailAccordion } from "~/components/area-riservata/comunicazioni";
import { Confirm } from "~/components/confirm";
import { AreaRiservataLayoutUserView } from "~/components/Layout";
import { Button } from "~/components/ui/button";
import {
	Popover,
	PopoverContent,
	PopoverTrigger,
} from "~/components/ui/popover";
import type { NextPageWithLayout } from "~/pages/_app";
import { useEnforcedSession } from "~/providers/SessionProvider";
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 ComunicazioniUserProps = {
	userId: UsersId;
};

const ComunicazioniUser: NextPageWithLayout<ComunicazioniUserProps> = ({
	userId,
}: ComunicazioniUserProps) => {
	const { user } = useEnforcedSession();
	const utils = api.useUtils();
	const { mutate } = api.comunicazioni.deleteAllUserEmails.useMutation({
		onError: (error) => {
			console.error(error);
			toast.error("Errore durante l'eliminazione delle comunicazioni");
		},
		onSuccess: async () => {
			toast.success("Comunicazioni eliminate");
			await utils.comunicazioni.getEmails.invalidate({ userId });
		},
	});

	return (
		<main className="flex flex-1 flex-col items-start gap-4">
			<div className="flex w-full items-center justify-between">
				<h3 className="font-bold text-2xl">Comunicazioni</h3>
				<Popover>
					<PopoverTrigger asChild>
						<Button size="sm">
							<MoreVertical />
						</Button>
					</PopoverTrigger>
					<PopoverContent
						align="end"
						className="flex w-fit flex-col items-center gap-4"
					>
						<Confirm
							description="Sei sicuro di voler eliminare tutte le comunicazioni?"
							onConfirm={() => {
								mutate({ userId });
							}}
							title="Elimina tutte le comunicazioni"
						>
							<Button
								aria-label="Delete Comunicazioni"
								className="w-full"
								size="sm"
								variant="destructive"
							>
								<Trash2 />
								<span>Elimina tutto</span>
							</Button>
						</Confirm>
					</PopoverContent>
				</Popover>
			</div>

			<EmailAccordion isAdmin={user.isAdmin} userId={userId} />
		</main>
	);
};

export default ComunicazioniUser;

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.comunicazioni.getEmails.prefetch({
			userId: parsed.data,
		});
		return {
			props: {
				userId: parsed.data,
				trpcState: helpers.trpc.dehydrate(),
			},
		};
	}
	return {
		notFound: true,
	};
}) satisfies GetServerSideProps<ComunicazioniUserProps>;

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