import { getPublicUser, MissionAutoClose, Prisma } from "@repo/db";
import { JsonValueType } from "@repo/db/zod";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { BaseNotification } from "_components/customToasts/BaseNotification";
import { editMissionAPI } from "_querys/missions";
import { MapStore } from "_store/mapStore";
import { Clock, X } from "lucide-react";
import { useSession } from "next-auth/react";
import toast, { Toast } from "react-hot-toast";

export const MissionAutoCloseToast = ({
	event,
	t,
	mapStore,
}: {
	event: MissionAutoClose;
	t: Toast;
	mapStore: MapStore;
}) => {
	const { data: session } = useSession();
	const queryClient = useQueryClient();
	const editMissionMutation = useMutation({
		mutationFn: ({ id, mission }: { id: number; mission: Partial<Prisma.MissionUpdateInput> }) =>
			editMissionAPI(id, mission),
		mutationKey: ["missions"],
		onSuccess: () => {
			queryClient.invalidateQueries({
				queryKey: ["missions"],
			});
		},
	});

	return (
		<BaseNotification icon={<Clock />} className="flex flex-row">
			<div className="flex-1">
				<h1 className="text-warning font-bold">Inaktiver Einsatz wurde automatisch geschlossen</h1>
				<p>{event.message}</p>
			</div>
			<div className="ml-11">
				<button
					className="btn"
					onClick={async () => {
						if (!session?.user) return;
						const mission = await editMissionMutation.mutateAsync({
							id: event.data.missionId,
							mission: {
								state: "running",
								missionLog: {
									push: {
										type: "reopened-log",
										timeStamp: new Date().toISOString(),
										data: {
											user: getPublicUser(session?.user, {
												ignorePrivacy: true,
											}) as unknown as JsonValueType,
										},
									},
								},
							},
						});
						mapStore.setMap({
							zoom: 14,
							center: {
								lat: mission.addressLat,
								lng: mission.addressLng,
							},
						});
						mapStore.setOpenMissionMarker({
							open: [
								{
									id: mission.id,
									tab: "home",
								},
							],
							close: [],
						});
						toast.dismiss(t.id);
					}}
				>
					schließen widerrufen
				</button>
				<button className="btn btn-ghost btn-sm" onClick={() => toast.remove(t.id)}>
					<X size={16} />
				</button>
			</div>
		</BaseNotification>
	);
};
