// pages/index.js
import { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import { useRecoilState , useRecoilValue} from "recoil";
import { readPoiMarkersStore } from "../store/selectors/readPoiMarkersStore"; // Aktualisiert mit atom
import { poiReadFromDbTriggerAtom } from '../store/atoms/poiReadFromDbTriggerAtom';

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

export default function Home() {
  const poiReadTrigger = useRecoilValue(poiReadFromDbTriggerAtom);
  const [locations, setLocations] = useRecoilState(readPoiMarkersStore);
  const [mParam, setMParam] = useState("");
  const [uParam, setUParam] = useState("");

  const loadData = async () => {
    try {
      const response = await fetch("/api/readLocations");
      if (!response.ok) {
        throw new Error("Fehler beim Laden der Standortdaten");
      }
      const data = await response.json();
      setLocations(data);
      console.log("Geladene Daten in Home.js:", data);
    } catch (error) {
      console.error(error.message);
    }
  };

  useEffect(() => {
    // URL-Parameter abfragen
    function getURLParameter(name) {
      const params = new URLSearchParams(window.location.search);
      return params.get(name);
    }
    setMParam(getURLParameter("m"));
    setUParam(getURLParameter("u"));

    // Daten beim Laden der Seite holen
    loadData();
    console.log("poiReadTrigger in Home.js:", poiReadTrigger);
  }, [poiReadTrigger]);

  const handleAddLocation = async (name, type, lat, lng) => {
    try {
      const response = await fetch("/api/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");
      }
      console.log("Standort erfolgreich hinzugefügt");
      loadData(); // Aktualisiere die Daten nach dem Hinzufügen
      console.log("poiReadTrigger in Home.js:", poiReadTrigger);
    } catch (error) {
      console.error(error.message);
    }
  };

  const handleLocationUpdate = (id, newLatitude, newLongitude) => {
    setLocations((prevLocations) =>
      prevLocations.map((location) =>
        location.idPoi === id
          ? { ...location, position: `POINT(${newLongitude} ${newLatitude})` }
          : location
      )
    );
  };
//------------------------------------
  // Daten beim Laden der Seite holen
  useEffect(() => {
    loadData();
    console.log("poiReadTrigger in Home.js:", poiReadTrigger);
  }, [poiReadTrigger]);
//------------------------------------
  return (
    <div>
      <MapComponentWithNoSSR
        locations={locations}
        onAddLocation={handleAddLocation}
        onLocationUpdate={handleLocationUpdate}
      />
    </div>
  );
}
