import { useMapStore } from "_store/mapStore";
import { useEffect } from "react";
import { Popup, useMap } from "react-leaflet";

export const ContextMenu = () => {
	const map = useMap();
	const { popup, map: mapStore, setPopup } = useMapStore();

	useEffect(() => {
		map.on("contextmenu", (e) => {
			setPopup({ isOpen: true, lat: e.latlng.lat, lng: e.latlng.lng });
		});
	}, [popup]);

	if (!popup) return null;

	return (
		<Popup position={[popup.lat, popup.lng]}>
			{/* // TODO: maske: */}
			<div>
				<button
					className="btn btn-sm"
					onClick={async () => {
						const address = await fetch(
							`https://nominatim.openstreetmap.org/reverse?lat=${popup.lat}&lon=${popup.lng}&format=json`,
						);
						const data = (await address.json()) as {
							address: {
								ISO3166_2_lvl4: string;
								country: string;
								country_code: string;
								county: string;
								hamlet: string;
								municipality: string;
								postcode: string;
								road: string;
								state: string;
								town: string;
							};
							display_name: string;
							importance: number;
							lat: string;
							licence: string;
							lon: string;
							name: string;
							osm_id: number;
							osm_type: string;
							place_id: number;
							place_rank: number;
							type: string;
						};
					}}
				>
					Neues Einsatz hier Erstellen
				</button>
			</div>
		</Popup>
	);
};
