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

import { fetchPoiMarkersThunk } from "../redux/thunks/database/pois/fetchPoiMarkersThunk";
import { addPoiThunk } from "../redux/thunks/database/pois/addPoiThunk";

import { selectPoiMarkers } from "../redux/slices/database/pois/poiMarkersSlice";
import { selectAddPoiStatus, selectAddPoiError } from "../redux/slices/database/pois/addPoiSlice";

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

export default function Home() {
  const dispatch = useDispatch();

  // Redux State
  const locations = useSelector(selectPoiMarkers);
  const poiReadTrigger = useSelector((state) => state.poiReadFromDbTrigger.trigger);
  const addPoiStatus = useSelector(selectAddPoiStatus);
  const addPoiError = useSelector(selectAddPoiError);

  // Lokale State (für URL-Parameter)
  const [mParam, setMParam] = useState("");
  const [uParam, setUParam] = useState("");

  // URL-Parameter auslesen und POIs laden
  useEffect(() => {
    const getURLParameter = (name) => {
      const params = new URLSearchParams(window.location.search);
      return params.get(name);
    };

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

    dispatch(fetchPoiMarkersThunk());
  }, [dispatch, poiReadTrigger]);

  // POI hinzufügen über Redux-Thunk
  const handleAddLocation = async (name, poiTypeId, lat, lng) => {
    const idLD = 0; // ⬅️ Falls IDLD dynamisch bestimmt werden soll, anpassen
    const formData = { name, poiTypeId, latitude: lat, longitude: lng, idLD };

    try {
      const resultAction = await dispatch(addPoiThunk(formData));
      if (addPoiThunk.fulfilled.match(resultAction)) {
        dispatch(fetchPoiMarkersThunk()); // neu laden
      } else {
        console.error("❌ Fehler beim Hinzufügen:", resultAction.payload);
      }
    } catch (error) {
      console.error("❌ Fehler im addPoiThunk:", error.message);
    }
  };

  return (
    <div>
      <MapComponentWithNoSSR locations={locations} onAddLocation={handleAddLocation} />
      <TestScriptWithNoSSR />

      {addPoiStatus === "failed" && <p className="text-red-600">❌ Fehler: {addPoiError}</p>}
    </div>
  );
}
