// /hooks/layers/useDynamicDeviceLayers.js
import { useEffect, useRef, useState } from "react";
import L from "leaflet";
import { createAndSetDevices } from "../utils/devices/createAndSetDevices";
import { checkOverlappingMarkers } from "../utils/mapUtils";
import plusRoundIcon from "@/components/icons/devices/overlapping/PlusRoundIcon";

/**
 * Dynamisch GIS-System-Marker erstellen & Sichtbarkeit steuern.
 * @param {object} map - Leaflet Map-Instanz
 * @param {Array} GisSystemStatic - Liste der Systeme aus Webservice
 * @param {object} mapLayersVisibility - Redux-Objekt mit Layer-Sichtbarkeiten
 * @param {object} priorityConfig - Konfig für Prioritäten
 * @returns {{ markerStates, layerRefs }} Alle Marker und Referenzen
 */
const useDynamicDeviceLayers = (map, GisSystemStatic, mapLayersVisibility, priorityConfig, oms) => {
  const [markerStates, setMarkerStates] = useState({});
  const layerRefs = useRef({});

  // Marker initialisieren (nicht sichtbar machen)
  useEffect(() => {
    if (!map || GisSystemStatic.length === 0) return;

    GisSystemStatic.forEach(({ Name, IdSystem }) => {
      const key = `system-${IdSystem}`; // Einheitlicher Key

      if (!layerRefs.current[key]) {
        layerRefs.current[key] = new L.LayerGroup().addTo(map);
      }

      createAndSetDevices(
        IdSystem,
        newMarkers => {
          const oldMarkers = markerStates[key];

          // Entferne alte Marker aus Karte und OMS
          if (oldMarkers && Array.isArray(oldMarkers)) {
            oldMarkers.forEach(marker => {
              if (map.hasLayer(marker)) {
                map.removeLayer(marker);
              }
              if (oms) {
                oms.removeMarker(marker);
              }
            });
          }

          // Neue Marker setzen
          setMarkerStates(prev => ({ ...prev, [key]: newMarkers }));
        },
        GisSystemStatic,
        priorityConfig,
        undefined,
        oms
      );
    });
  }, [map, GisSystemStatic, priorityConfig]);

  // Sichtbarkeit nach Redux-Status steuern
  useEffect(() => {
    if (!map) return;
    const editMode = localStorage.getItem("editMode") === "true";

    Object.entries(markerStates).forEach(([key, markers]) => {
      const isVisible = mapLayersVisibility[key];
      markers.forEach(marker => {
        const hasLayer = map.hasLayer(marker);
        if (editMode || !isVisible) {
          if (hasLayer) map.removeLayer(marker);
        } else {
          if (!hasLayer) marker.addTo(map);
        }
      });
    });

    const allMarkers = Object.values(markerStates).filter(Array.isArray).flat();

    checkOverlappingMarkers(map, allMarkers, plusRoundIcon);
  }, [map, markerStates, mapLayersVisibility]);

  return { markerStates, layerRefs };
};

export default useDynamicDeviceLayers;
