import { useState } from "react";
import toast from "react-hot-toast";
import { NewRinnovoModal } from "~/components/servizio/rinnovo";
import { FormServizio, type FormValues } from "~/forms/FormServizio";
import type { UsersId } from "~/schemas/public/Users";
import { api } from "~/utils/api";
import { Button } from "../ui/button";
import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogHeader,
	DialogTitle,
	DialogTrigger,
} from "../ui/dialog";

export const ServiziHeader = ({ userId }: { userId: UsersId }) => {
	return (
		<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>
	);
};

const NewServizioModal = ({ userId }: { userId: UsersId }) => {
	const [open, setOpen] = useState(false);
	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.invalidate();

			setOpen(false);
		},
	});

	function onSubmit(fields: FormValues) {
		add({ data: { ...fields, user_id: userId } });
	}
	return (
		<Dialog onOpenChange={setOpen} open={open}>
			<DialogTrigger asChild>
				<Button
					onClick={() => {
						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">
					<FormServizio
						initialData={undefined}
						isLimited={false}
						onSubmit={onSubmit}
					/>
				</div>
			</DialogContent>
		</Dialog>
	);
};
