// components/AddPOIModal.js
import React, { useState, useEffect, use } from "react";
import ReactDOM from "react-dom";
import { setPoiMarkers } from "../../redux/slices/readPoiMarkersStoreSlice";
import { selectGisStationsStaticDistrict } from "../../redux/slices/webservice/gisStationsStaticDistrictSlice";
import { useDispatch, useSelector } from "react-redux";
import { fetchPoiTypes } from "../../redux/slices/database/poiTypesSlice";
import { incrementTrigger } from "../../redux/slices/poiReadFromDbTriggerSlice";

const AddPOIModal = ({ onClose, map, latlng }) => {
  const dispatch = useDispatch();

  const poiTypData = useSelector((state) => state.poiTypes.data);

  const [name, setName] = useState("");
  const [poiTypeId, setPoiTypeId] = useState(""); // Initialize as string
  const [poiTypeName, setPoiTypeName] = useState(""); // Initialize as string

  const [latitude] = useState(latlng.lat.toFixed(5));
  const [longitude] = useState(latlng.lng.toFixed(5));

  const [deviceName, setDeviceName] = useState("");
  //-----------------------------------------------------
  useEffect(() => {
    const fetchpoiTypData = async () => {
      try {
        const response = await fetch("/api/talas_v5_DB/poiTyp/readPoiTyp");
        const data = await response.json();
        setpoiTypData(data);

        if (data && data.length > 0) {
          console.log("POI-Typen geladen:", data);
          setPoiTypeId(data[0].idPoiTyp); // Setzt den ersten Typ
          setPoiTypeName(data[0].name);
        }
      } catch (error) {
        console.error("Fehler beim Abrufen der poiTyp Daten:", error);
      }
    };

    fetchpoiTypData();
  }, []);

  useEffect(() => {
    if (poiTypData.length > 0 && !poiTypeId) {
      setPoiTypeId(poiTypData[0].idPoiTyp);
    }
  }, [poiTypData]);
  useEffect(() => {
    console.log("Aktueller POI Type:", poiTypeId);
  }, [poiTypeId]);

  //------------------------------------------------------------------------------------------
  const gisStationsStatic = useSelector(selectGisStationsStaticDistrict);
  const locationDeviceData = gisStationsStatic?.Points ?? [];

  console.log("gisStationsStatic aus AddPOIModal:", gisStationsStatic);

  useEffect(() => {
    if (locationDeviceData?.length > 0) {
      console.log("🎯 Gerätedaten erfolgreich geladen:", locationDeviceData);
      setDeviceName((prev) => prev || locationDeviceData[0]?.LD_Name || "");
    }
  }, [locationDeviceData]);

  //------------------------------------------------------------------------------------------
  //-----------------handleSubmit-------------------
  const handleSubmit = async (event) => {
    event.preventDefault();
    const formData = {
      name,
      poiTypeId: Number(poiTypeId), // Umwandlung in eine Zahl
      latitude,
      longitude,
      idLD: locationDeviceData.find((device) => device.LD_Name === deviceName)?.IdLD,
    };

    const response = await fetch("/api/talas_v5_DB/pois/addLocation", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(formData),
    });

    if (response.ok) {
      dispatch(incrementTrigger());
      onClose();
      window.location.reload();
    } else {
      console.error("Fehler beim Hinzufügen des POI");
    }

    if (map && typeof map.closePopup === "function") {
      map.closePopup();
    }
    //Seite neu laden
    window.location.reload();
  };
  //-----------------
  // POI-Typen aus Redux laden, wenn die Komponente gemountet wird
  useEffect(() => {
    dispatch(fetchPoiTypes());
  }, [dispatch]);

  //---------------------

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center z-[1000]" onClick={onClose}>
      <div className="relative bg-white p-6 rounded-lg shadow-lg w-96 max-w-full" onClick={(e) => e.stopPropagation()}>
        {/* Schließen-Button */}
        <button onClick={onClose} className="absolute top-2 right-2 text-gray-600 hover:text-gray-900">
          ✖
        </button>

        {/* Modal-Inhalt */}
        <form onSubmit={handleSubmit} className="m-0 p-2 w-full">
          <div className="flex items-center mb-4">
            <label htmlFor="name" className="block mr-2 flex-none">
              Name:
            </label>
            <input type="text" id="name" name="name" value={name} onChange={(e) => setName(e.target.value)} placeholder="Name der Station" className="block p-2 w-full border-2 border-gray-200 rounded-md text-sm" />
          </div>

          <div className="flex items-center mb-4">
            <label htmlFor="deviceName" className="block mr-2 flex-none">
              Gerät:
            </label>
            <select id="deviceName" name="deviceName" value={deviceName} onChange={(e) => setDeviceName(e.target.value)} className="block p-2 w-full border-2 border-gray-200 rounded-md text-sm">
              <option value="">-- Gerät auswählen --</option>
              {locationDeviceData?.length > 0 ? (
                locationDeviceData.map((device, index) => (
                  <option key={device?.IdLD || index} value={device?.LD_Name}>
                    {device?.LD_Name || "Unbekanntes Gerät"}
                  </option>
                ))
              ) : (
                <option disabled>Keine Geräte gefunden</option>
              )}
            </select>
          </div>
          <div className="flex items-center mb-4">
            <label htmlFor="idPoiTyp2" className="block mr-2 flex-none">
              Typ:
            </label>
            <select
              id="idPoiTyp2"
              name="idPoiTyp2"
              value={poiTypeId}
              onChange={(e) => setPoiTypeId(Number(e.target.value))} // Hier ebenfalls umwandeln
              className="block p-2 w-full border-2 border-gray-200 rounded-md text-sm"
            >
              {poiTypData.length === 0 ? (
                <option value="" disabled>
                  Keine POI-Typen verfügbar
                </option>
              ) : (
                poiTypData.map((poiTyp) => (
                  <option key={poiTyp.idPoiTyp} value={poiTyp.idPoiTyp}>
                    {poiTyp.name}
                  </option>
                ))
              )}
            </select>
          </div>

          <div className="flex justify-between text-sm text-gray-700 mb-4">
            <span>Lat: {latitude}</span>
            <span>Lng: {longitude}</span>
          </div>

          <button type="submit" className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded w-full">
            POI hinzufügen
          </button>
        </form>
      </div>
    </div>
  );
};

export default AddPOIModal;
