"use client"; // /components/main/einausgaenge/modals/InputModal.tsx import React, { useEffect, useState } from "react"; import { useSelector, useDispatch } from "react-redux"; import { RootState } from "../../../../redux/store"; import { updateInvertierung, updateName, } from "../../../../redux/slices/digitalInputsSlice"; export default function InputModal({ selectedInput, closeInputModal, isOpen }) { const dispatch = useDispatch(); const reduxInput = useSelector((state: RootState) => state.digitalInputsSlice.inputs.find( (input) => input.id === Number(selectedInput?.id) ) ); const [isInitialLoad, setIsInitialLoad] = useState(true); const [name, setName] = useState(""); const [invertiert, setInvertiert] = useState(false); const [filterzeit, setFilterzeit] = useState(0); const [gewichtung, setGewichtung] = useState(0); const [zaehlerAktiv, setZaehlerAktiv] = useState(false); useEffect(() => { if (reduxInput && isInitialLoad) { setName(reduxInput.name || ""); setInvertiert(reduxInput.invertierung); setFilterzeit(reduxInput.filterzeit); setGewichtung(reduxInput.gewichtung); setZaehlerAktiv(reduxInput.zaehlerAktiv); setIsInitialLoad(false); } }, [reduxInput, isInitialLoad]); if (!isOpen || !selectedInput || !reduxInput) return null; const handleSpeichern = async () => { const updates: any = { id: reduxInput.id }; let hasChange = false; if (name !== reduxInput.name) { updates.name = name; dispatch(updateName({ id: reduxInput.id, name })); hasChange = true; } if (invertiert !== reduxInput.invertierung) { updates.invertierung = invertiert ? 1 : 0; dispatch( updateInvertierung({ id: reduxInput.id, invertierung: invertiert }) ); hasChange = true; } if (filterzeit !== reduxInput.filterzeit) { updates.filterzeit = filterzeit; hasChange = true; } if (gewichtung !== reduxInput.gewichtung) { updates.gewichtung = gewichtung; hasChange = true; } if (zaehlerAktiv !== reduxInput.zaehlerAktiv) { updates.zaehlerAktiv = zaehlerAktiv ? 1 : 0; hasChange = true; } if (!hasChange) { alert("⚠️ Keine Änderungen erkannt."); return; } try { const res = await fetch("/api/cpl/updateDigitaleEingaenge", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(updates), }); if (!res.ok) { const errData = await res.json(); throw new Error(errData.error || "Unbekannter Fehler"); } setIsInitialLoad(true); // Reset closeInputModal(); // Modal schließen bei Erfolg } catch (err: any) { alert("❌ Fehler beim Speichern: " + err.message); } }; const handleClose = () => { setIsInitialLoad(true); closeInputModal(); }; return (