import { useMapStore } from "_store/mapStore";
import { Marker as LMarker } from "leaflet";
import { Ref, use, useEffect, useRef } from "react";
import { Marker, Polygon, Polyline, Popup } from "react-leaflet";
import L from "leaflet";

export const SearchElements = () => {
	const { searchElements, searchPopup, setSearchPopup, setPopup } =
		useMapStore();
	const poppupRef = useRef<LMarker>(null);

	useEffect(() => {
		if (searchPopup?.isOpen) {
			poppupRef.current?.openPopup();
		} else {
			poppupRef.current?.closePopup();
		}
	}, [searchPopup]);

	const SearchElement = ({
		element,
	}: {
		element: (typeof searchElements)[1];
	}) => {
		const ref = useRef<any>(null);

		useEffect(() => {
			if (ref.current) {
				ref.current.on("click", () => {
					const center = ref.current.getBounds().getCenter();
					setSearchPopup({
						isOpen: true,
						lat: center.lat,
						lng: center.lng,
						elementId: element.id,
					});
					setPopup(null);
				});
			}
		}, []);

		return (
			<Polygon
				key={element.id}
				positions={element.nodes.map((node) => [node.lat, node.lon])}
				color={searchPopup?.elementId === element.id ? "#ff4500" : "#46b7a3"}
				ref={ref}
			/>
		);
	};
	console.log("searchPopup", searchPopup);
	const searchPopupElement = searchElements.find(
		(element) => element.id === searchPopup?.elementId,
	);
	console.log("searchPopupElement", searchPopupElement);
	return (
		<>
			{searchElements.map((element) => {
				return <SearchElement key={element.id} element={element} />;
			})}
			{searchPopup && (
				<Marker
					position={[searchPopup.lat, searchPopup.lng]}
					ref={poppupRef}
					icon={new L.DivIcon()}
					opacity={0}
				>
					<Popup>
						<div className="absolute z-1000 opacity-100 pointer-events-auto w-[250px] text-white border-rescuetrack border-2 bg-base-100/70">
							<div className="p-1 text-xl text-center">OSM-Element</div>
						</div>
					</Popup>
				</Marker>
			)}
		</>
	);
};
