import type { GetServerSideProps } from "next";
import { useState } from "react";
import toast from "react-hot-toast";
import { AreaRiservataLayoutUserView } from "~/components/Layout";
import { TabServizio } from "~/components/tables/servizio-table";
import { Button } from "~/components/ui/button";
import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogHeader,
	DialogTitle,
	DialogTrigger,
} from "~/components/ui/dialog";
import { FormNewServizio, type FormValues } from "~/forms/FormNewServizio";
import type { NextPageWithLayout } from "~/pages/_app";
import type { Servizio } from "~/schemas/public/Servizio";
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 ServizioUserProps = {
	userId: UsersId;
};
const ServizioUser: NextPageWithLayout<ServizioUserProps> = ({
	userId,
}: ServizioUserProps) => {
	const [open, setOpen] = useState(false);
	const [editData, setEditData] = useState<Servizio | undefined>(undefined);
	return (
		<div className="mx-auto max-w-8xl grow space-y-4">
			<div className="flex justify-between">
				<h3 className="font-bold text-2xl">Servizi Utente</h3>
				<NewServizioModal
					editData={editData}
					open={open}
					setEditData={setEditData}
					setOpen={setOpen}
					userId={userId}
				/>
			</div>
			<TabServizio
				setEditData={setEditData}
				setOpen={setOpen}
				userId={userId}
			/>
		</div>
	);
};
export default ServizioUser;

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.getUserServizi.prefetch({
			userId: parsed.data,
		});

		return {
			props: {
				userId: parsed.data,
				trpcState: helpers.trpc.dehydrate(),
			},
		};
	}
	return {
		notFound: true,
	};
}) satisfies GetServerSideProps<ServizioUserProps>;
ServizioUser.getLayout = function getLayout(page) {
	return <AreaRiservataLayoutUserView>{page}</AreaRiservataLayoutUserView>;
};

const NewServizioModal = ({
	userId,
	editData,

	setEditData,
	open,
	setOpen,
}: {
	userId: UsersId;
	editData: Servizio | undefined;
	setEditData: (data: Servizio | undefined) => void;
	open: boolean;
	setOpen: (open: boolean) => void;
}) => {
	const utils = api.useUtils();

	const { mutate: add } = api.servizio.addServizio.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async () => {
			toast.success("Servizio creato con successo");
			await utils.servizio.getUserServizi.invalidate();
			setEditData(undefined);
			setOpen(false);
		},
	});

	const { mutate: update } = api.servizio.updateServizio.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async (data) => {
			toast.success("Servizio modificato con successo");
			await utils.servizio.getUserServizi.invalidate();
			await utils.servizio.getAllServizioAnnunci.invalidate({ userId });
			await utils.servizio.getServizio.invalidate({
				servizioId: data.servizio_id,
			});
			await utils.servizio.getCompatibileAnnunci.invalidate({
				servizioId: data.servizio_id,
			});
			await utils.servizio.getPacksSolution.invalidate({
				servizioId: data.servizio_id,
			});
			setEditData(undefined);
			setOpen(false);
		},
	});
	function onSubmit(fields: FormValues) {
		if (editData) {
			update({
				data: {
					...fields,
				},
				servizioId: editData.servizio_id,
			});
		} else {
			add({ data: { ...fields, user_id: userId } });
		}
	}
	return (
		<Dialog onOpenChange={setOpen} open={open}>
			<DialogTrigger asChild>
				<Button
					onClick={() => {
						setEditData(undefined);
						setOpen(true);
					}}
					variant="outline"
				>
					Nuovo Servizio
				</Button>
			</DialogTrigger>
			<DialogContent className="max-h-[80%] w-full overflow-auto p-4 sm:max-w-5xl">
				<DialogHeader>
					<DialogTitle>Creazione Servizio</DialogTitle>
					<DialogDescription className="sr-only">desc</DialogDescription>
				</DialogHeader>
				<div className="overflow-y-auto">
					<FormNewServizio
						initialData={editData}
						isLimited={false}
						onSubmit={onSubmit}
					/>
				</div>
			</DialogContent>
		</Dialog>
	);
};
