// /components/pois/AddPOIModal.js
import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { selectGisStationsStaticDistrict } from "../../redux/slices/webservice/gisStationsStaticDistrictSlice";
import { fetchPoiTypThunk } from "../../redux/thunks/database/pois/fetchPoiTypThunk";
import { incrementTrigger } from "../../redux/slices/database/pois/poiReadFromDbTriggerSlice";
import { addPoiThunk } from "../../redux/thunks/database/pois/addPoiThunk";
import { resetAddPoiStatus } from "../../redux/slices/database/pois/addPoiSlice";
import { fetchPoiIconsDataThunk } from "../../redux/thunks/database/pois/fetchPoiIconsDataThunk";

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

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

  const [name, setName] = useState("");
  const [poiTypeId, setPoiTypeId] = useState("");
  const [deviceName, setDeviceName] = useState("");

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

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

  useEffect(() => {
    if (poiTypData.length > 0 && !poiTypeId) {
      setPoiTypeId(poiTypData[0].idPoiTyp);
    }
  }, [poiTypData]);

  useEffect(() => {
    if (locationDeviceData?.length > 0) {
      setDeviceName((prev) => prev || locationDeviceData[0]?.LD_Name || "");
    }
  }, [locationDeviceData]);

  useEffect(() => {
    dispatch(fetchPoiTypThunk());
  }, [dispatch]);

  const handleSubmit = async (event) => {
    event.preventDefault();

    const formData = {
      name,
      poiTypeId: Number(poiTypeId),
      latitude,
      longitude,
      idLD: locationDeviceData.find((device) => device.LD_Name === deviceName)?.IdLD,
    };

    try {
      await dispatch(addPoiThunk(formData)).unwrap();
      dispatch(incrementTrigger());
      dispatch(resetAddPoiStatus()); // ✅ Status zurücksetzen
      onClose();

      // Icons im Hintergrund nachladen
      setTimeout(() => {
        dispatch(fetchPoiIconsDataThunk());
      }, 100);
    } catch (error) {
      console.error("Fehler beim Hinzufügen des POI:", error);
    }

    if (map?.closePopup) {
      map.closePopup();
    }
  };

  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()}>
        <button onClick={onClose} className="absolute top-2 right-2 text-gray-600 hover:text-gray-900">
          ✖
        </button>

        <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.map((device, index) => (
                <option key={device?.IdLD || index} value={device?.LD_Name}>
                  {device?.LD_Name || "Unbekanntes Gerät"}
                </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))} 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>

          {status === "loading" && <div className="text-blue-500 mb-2 text-sm">Wird hinzugefügt...</div>}
          {status === "failed" && error && <div className="text-red-500 mb-2 text-sm">❌ Fehler: {error}</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;
