import { useMapStore } from "_store/mapStore";
import { Marker, Polygon, Popup } from "react-leaflet";
import { useQuery } from "@tanstack/react-query";
import { getMissionsAPI } from "_querys/missions";
import { usePannelStore } from "_store/pannelStore";
import { OSMWay } from "@repo/db";
import { useEffect } from "react";

export const SearchElements = () => {
	const { searchElements, openMissionMarker, setSearchElements } = useMapStore();
	const { isOpen: pannelOpen, editingMissionId } = usePannelStore((state) => state);
	const { data: missions } = useQuery({
		queryKey: ["missions"],
		queryFn: () =>
			getMissionsAPI({
				OR: [
					{
						state: "draft",
					},
					{
						state: "running",
					},
				],
			}),
	});

	useEffect(() => {
		if (pannelOpen) {
			const missionEdited = missions?.find((m) => m.id === editingMissionId);
			console.log("Mission Edited", missionEdited, editingMissionId, missions);
			if (missionEdited) {
				const elements = missionEdited.addressOSMways.map((e) => ({
					...(e as unknown as OSMWay),
					isSelected: true,
				}));
				setSearchElements(elements);
			} else {
				setSearchElements([]);
			}
		} else {
			const openMissions = openMissionMarker.map((m) => {
				const mission = missions?.find((mi) => mi.id === m.id);
				return mission;
			});
			const elements = openMissions
				.filter((m) => m?.addressOSMways)
				.flatMap((m) =>
					m?.addressOSMways.map((e) => ({
						...(e as unknown as OSMWay),
						isSelected: true,
					})),
				);
			setSearchElements(elements.filter((e) => !!e));
		}
	}, [openMissionMarker, pannelOpen, missions]);

	const SearchElement = ({ element }: { element: OSMWay }) => {
		const { toggleSearchElementSelection } = useMapStore();
		if (!element.nodes) return null;
		return (
			<Polygon
				positions={element.nodes.map((node) => [node.lat, node.lon])}
				color={element.isSelected ? "#ff4500" : "#46b7a3"}
				eventHandlers={{
					click: () => {
						if (!pannelOpen) return;
						toggleSearchElementSelection(element.wayID);
					},
				}}
			/>
		);
	};

	return (
		<>
			{searchElements.map((element, i) => {
				return <SearchElement key={`mission-elem-${element.wayID}-${i}`} element={element} />;
			})}
		</>
	);
};
