"use client";
import { usePannelStore } from "_store/pannelStore";
import { Marker } from "react-leaflet";
import L from "leaflet";
import { useQuery } from "@tanstack/react-query";
import { getMissionsAPI } from "_querys/missions";
import { HPGValidationRequired } from "_helpers/hpgValidationRequired";
import { getConnectedAircraftsAPI } from "_querys/aircrafts";
import { useMapStore } from "_store/mapStore";

export const MapAdditionals = () => {
	const { isOpen, missionFormValues } = usePannelStore((state) => state);
	const { data: missions = [] } = useQuery({
		queryKey: ["missions"],
		queryFn: () =>
			getMissionsAPI({
				OR: [{ state: "draft" }, { state: "running" }],
			}),
		refetchInterval: 10_000,
	});
	const mapStore = useMapStore((state) => state);

	const { data: aircrafts } = useQuery({
		queryKey: ["aircrafts"],
		queryFn: () => getConnectedAircraftsAPI(),
		refetchInterval: 10000,
	});

	const markersNeedingAttention = missions.filter(
		(m) =>
			HPGValidationRequired(m.missionStationIds, aircrafts, m.hpgMissionString) &&
			m.hpgValidationState === "POSITION_AMANDED" &&
			m.state === "draft" &&
			m.hpgLocationLat &&
			m.hpgLocationLng,
	);

	return (
		<>
			{missionFormValues?.addressLat && missionFormValues?.addressLng && isOpen && (
				<Marker
					position={[missionFormValues.addressLat, missionFormValues.addressLng]}
					icon={L.icon({
						iconUrl: "/icons/mapMarker.png",
						iconSize: [40, 40],
						iconAnchor: [20, 35],
					})}
					interactive={false}
				/>
			)}
			{markersNeedingAttention.map((mission) => (
				<Marker
					key={mission.id}
					position={[mission.hpgLocationLat!, mission.hpgLocationLng!]}
					icon={L.icon({
						iconUrl: "/icons/mapMarker.png",
						iconSize: [40, 40],
						iconAnchor: [20, 35],
					})}
					eventHandlers={{
						click: () =>
							mapStore.setOpenMissionMarker({
								open: [
									{
										id: mission.id,
										tab: "home",
									},
								],
								close: [],
							}),
					}}
				/>
			))}
		</>
	);
};
