// components/TanstackProvider.tsx
"use client";

import { toast } from "react-hot-toast";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactNode, useEffect, useRef, useState } from "react";
import { dispatchSocket } from "(app)/dispatch/socket";
import { NotificationPayload } from "@repo/db";
import { HPGnotificationToast } from "_components/customToasts/HPGnotification";
import { useMapStore } from "_store/mapStore";
import { AdminMessageToast } from "_components/customToasts/AdminMessage";
import { pilotSocket } from "(app)/pilot/socket";
import { QUICK_RESPONSE, StatusToast } from "_components/customToasts/StationStatusToast";
import { MissionAutoCloseToast } from "_components/customToasts/MissionAutoClose";

export function QueryProvider({ children }: { children: ReactNode }) {
	const mapStore = useMapStore((s) => s);
	const notificationSound = useRef<HTMLAudioElement | null>(null);

	const [queryClient] = useState(
		() =>
			new QueryClient({
				defaultOptions: {
					mutations: {
						onError: (error) => {
							toast.error("Ein Fehler ist aufgetreten: " + (error as Error).message, {
								position: "top-right",
							});
						},
					},
				},
			}),
	);
	useEffect(() => {
		notificationSound.current = new Audio("/sounds/notification.mp3");
	}, []);
	useEffect(() => {
		const invalidateMission = () => {
			queryClient.invalidateQueries({
				queryKey: ["missions"],
			});
		};

		const invalidateConnectedUsers = () => {
			queryClient.invalidateQueries({
				queryKey: ["connected-users"],
			});
			queryClient.invalidateQueries({
				queryKey: ["aircrafts"],
			});
			queryClient.invalidateQueries({
				queryKey: ["dispatchers"],
			});
		};

		const invalidateConenctedAircrafts = () => {
			queryClient.invalidateQueries({
				queryKey: ["aircrafts"],
			});
			queryClient.invalidateQueries({
				queryKey: ["missions"],
			});
		};

		const handleNotification = (notification: NotificationPayload) => {
			const playNotificationSound = () => {
				if (notificationSound.current) {
				notificationSound.current.currentTime = 0;
				notificationSound.current
					.play()
					.catch((e) => console.error("Notification sound error:", e));
			}
			}

			switch (notification.type) {
				case "hpg-validation":
					playNotificationSound();
					toast.custom(
						(t) => <HPGnotificationToast event={notification} mapStore={mapStore} t={t} />,
						{
							duration: 15000,
						},
					);

					break;
				case "admin-message":
					playNotificationSound();
					toast.custom((t) => <AdminMessageToast event={notification} t={t} />, {
						duration: 999999,
					});
					break;
				case "station-status":
					if (!QUICK_RESPONSE[notification.status]) return;
					toast.custom((e) => <StatusToast event={notification} t={e} />, {
						duration: 60000,
					});
					break;
				case "mission-auto-close":
					playNotificationSound();
					toast.custom(
						(t) => <MissionAutoCloseToast event={notification} t={t} mapStore={mapStore} />,
						{
							duration: 60000,
						},
					);
					break;
				case "mission-closed":
					toast("Dein aktueller Einsatz wurde geschlossen.");
					
					break;
				default:
					toast("unbekanntes Notification-Event");
					break;
			}
		};

		dispatchSocket.on("update-mission", invalidateMission);
		dispatchSocket.on("delete-mission", invalidateMission);
		dispatchSocket.on("new-mission", invalidateMission);
		dispatchSocket.on("dispatchers-update", invalidateConnectedUsers);
		dispatchSocket.on("pilots-update", invalidateConnectedUsers);
		dispatchSocket.on("update-connectedAircraft", invalidateConenctedAircrafts);
		dispatchSocket.on("notification", handleNotification);
		pilotSocket.on("notification", handleNotification);

		return () => {
			dispatchSocket.off("update-mission", invalidateMission);
			dispatchSocket.off("delete-mission", invalidateMission);
			dispatchSocket.off("new-mission", invalidateMission);
			dispatchSocket.off("dispatchers-update", invalidateConnectedUsers);
			dispatchSocket.off("pilots-update", invalidateConnectedUsers);
			dispatchSocket.off("update-connectedAircraft", invalidateConenctedAircrafts);
			dispatchSocket.off("notification", handleNotification);
			pilotSocket.off("notification", handleNotification);
		};
	}, [queryClient, mapStore]);

	return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
}
