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

import { toast } from "react-hot-toast";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactNode, useEffect, useState } from "react";
import { dispatchSocket } from "dispatch/socket";
import { Mission } from "@repo/db";

export function QueryProvider({ children }: { children: ReactNode }) {
	const [queryClient] = useState(
		() =>
			new QueryClient({
				defaultOptions: {
					mutations: {
						onError: (error) => {
							toast.error("An error occurred: " + (error as Error).message, {
								position: "top-right",
							});
						},
					},
				},
			}),
	);
	useEffect(() => {
		const invalidateMission = (mission: Mission) => {
			queryClient.invalidateQueries({
				queryKey: ["missions"],
			});
		};

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

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

		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);
	}, [queryClient]);

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