// utils/setupPOIs.js
import { parsePoint } from "./geometryUtils";
import { handleEditPoi } from "./poiUtils";
import { updateLocationInDatabaseService } from "../services/database/updateLocationInDatabaseService";
import { setSelectedPoi, clearSelectedPoi } from "../redux/slices/database/pois/selectedPoiSlice";
import { cleanupMarkers } from "@/utils/common/cleanupMarkers";

export const setupPOIs = async (
  map,
  pois,
  poiData, // enthält aktuell: idPoi + path
  poiTypMap,
  userRights,
  poiLayerRef,
  setSelectedPoi,
  setLocationDeviceData,
  setDeviceName,
  setCurrentPoi,
  poiLayerVisible,
  fetchPoiData,
  toast,
  setShowPoiUpdateModal,
  setCurrentPoiData,
  deviceName,
  dispatch
) => {
  const editMode = localStorage.getItem("editMode") === "true";
  userRights = editMode ? userRights : undefined;

  // ✅ Mapping vorbereiten: idPoi → icon path
  const iconMap = new Map();
  poiData.forEach(item => {
    if (item.idPoi && item.path) {
      iconMap.set(item.idPoi, item.path);
    }
  });

  if (map && poiLayerRef.current) {
    const existingMarkers = poiLayerRef.current?.getLayers?.();
    if (existingMarkers?.length) {
      cleanupMarkers(existingMarkers);
    }
    map.removeLayer(poiLayerRef.current);
    poiLayerRef.current = new L.LayerGroup().addTo(map);

    for (const poi of pois) {
      try {
        const { latitude, longitude } = parsePoint(poi.position);
        const poiTypName = poiTypMap.get(poi.idPoiTyp) || "Unbekannt";
        const canDrag = userRights ? userRights.some(r => r.IdRight === 56) : false;

        // ✅ Icon korrekt über idPoi auflösen
        const iconPath = iconMap.get(poi.idPoi);
        const iconUrl = iconPath
          ? `/img/icons/pois/${iconPath}`
          : "/img/icons/pois/default-icon.png";

        const marker = L.marker([latitude, longitude], {
          icon: L.icon({
            iconUrl: iconUrl,
            iconSize: [25, 41],
            iconAnchor: [12, 41],
            popupAnchor: [1, -34],
          }),
          draggable: canDrag,
          id: poi.idPoi,
          name: poi.name,
          description: poi.description,
          idLD: poi.idLD,
          idPoiTyp: poi.idPoiTyp,
          link: poi.link,
        });

        if (editMode) {
          marker.bindContextMenu({
            contextmenu: true,
            contextmenuWidth: 140,
            contextmenuItems: [
              {
                text: "POI Bearbeiten",
                icon: "/img/poi-edit.png",
                callback: () =>
                  handleEditPoi(
                    marker,
                    userRights,
                    setCurrentPoiData,
                    setShowPoiUpdateModal,
                    fetchPoiData,
                    toast
                  ),
              },
            ],
          });
        }

        marker.bindTooltip(
          `
          <div class="bg-white text-gray-800 text-sm rounded-xl px-4 py-2 w-56">
            <div class="font-semibold text-blue-500 mb-1">${poi.description || "Unbekannt"}</div>
            <div class="text-gray-600 text-sm">Gerät: ${deviceName || "unbekannt"}</div>
            <div class="text-gray-600 text-sm">Typ: ${poiTypName}</div>
          </div>
          `,
          {
            direction: "top",
            offset: [0, -10],
            opacity: 0.95,
            sticky: true,
          }
        );

        marker.on("mouseover", function () {
          dispatch(setSelectedPoi(poi));
          localStorage.setItem("lastElementType", "marker");
          localStorage.setItem("markerLink", this.options.link);
        });

        marker.on("mouseout", function () {
          dispatch(clearSelectedPoi());
          //this.closePopup();
        });

        marker.on("dragend", e => {
          if (canDrag) {
            const newLat = e.target.getLatLng().lat;
            const newLng = e.target.getLatLng().lng;
            const markerId = e.target.options.id;
            updateLocationInDatabaseService(markerId, newLat, newLng);
          } else {
            console.error("Drag operation not allowed");
          }
        });

        if (poiLayerVisible) {
          marker.addTo(poiLayerRef.current);
        }
      } catch (error) {
        console.error("❌ Fehler bei POI Marker:", error);
      }
    }
  }
};
