"use client";
import React, { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import { setPoiMarkers } from "../redux/slices/readPoiMarkersStoreSlice.js";
import { useSelector, useDispatch } from "react-redux";

const MapComponentWithNoSSR = dynamic(() => import("../components/mainComponent/MapComponent"), { ssr: false });
const TestScriptWithNoSSR = dynamic(() => import("../components/TestScript"), { ssr: false });

export default function Home() {
  const poiReadTrigger = useSelector((state) => state.poiReadFromDbTrigger.trigger);
  const dispatch = useDispatch();
  const locations = useSelector((state) => state.readPoiMarkersStore.poiMarkers);
  const [mParam, setMParam] = useState("");
  const [uParam, setUParam] = useState("");

  // Daten abrufen
  const loadData = async () => {
    try {
      const response = await fetch("/api/talas_v5_DB/pois/readLocations");
      if (!response.ok) {
        throw new Error("Fehler beim Laden der Standortdaten");
      }
      const data = await response.json();
      dispatch(setPoiMarkers(data));
    } catch (error) {
      console.error(error.message);
    }
  };

  // Verhindert mehrfaches Laden durch doppelte Registrierung
  useEffect(() => {
    let isMounted = true;

    function getURLParameter(name) {
      const params = new URLSearchParams(window.location.search);
      return params.get(name);
    }

    setMParam(getURLParameter("m"));
    setUParam(getURLParameter("u"));

    const fetchData = async () => {
      await loadData();
    };

    if (isMounted) {
      fetchData();
    }

    return () => {
      isMounted = false;
    };
  }, [poiReadTrigger]); // Nur einmal bei Änderung von poiReadTrigger ausführen

  // POI hinzufügen
  const handleAddLocation = async (name, type, lat, lng) => {
    try {
      const response = await fetch("/api/talas_v5_DB/pois/addLocation", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, type, latitude: lat, longitude: lng }),
      });
      if (!response.ok) {
        throw new Error("Fehler beim Hinzufügen des Standorts");
      }
      loadData();
    } catch (error) {
      console.error(error.message);
    }
  };

  // Standort aktualisieren
  const handleLocationUpdate = (id, newLatitude, newLongitude) => {
    setLocations((prevLocations) => prevLocations.map((location) => (location.idPoi === id ? { ...location, position: `POINT(${newLongitude} ${newLatitude})` } : location)));
  };

  return (
    <div>
      <MapComponentWithNoSSR locations={locations} onAddLocation={handleAddLocation} onLocationUpdate={handleLocationUpdate} />
      <TestScriptWithNoSSR />
    </div>
  );
}
