"use client"; ///pages/analogeEingaenge.tsx
import React, { useState, useEffect } from "react";
import AnalogeEingaengeTabelle from "../components/main/analogeEingaenge/AnalogeEingaengeTable";
import AnalogInputsChart from "../components/main/analogeEingaenge/AnalogInputsChart";
import AnalogInputsSettingsModal from "../components/main/analogeEingaenge/AnalogInputsSettingsModal";
import { fetchAnalogeEingaengeThunk } from "../redux/thunks/fetchAnalogeEingaengeThunk";
import { useAppDispatch } from "../redux/store";

function AnalogeEingaenge() {
  const [selectedId, setSelectedId] = useState<number | null>(null);
  const [selectedInput, setSelectedInput] = useState<any | null>(null);
  const [isSettingsModalOpen, setIsSettingsModalOpen] = useState(false);
  const dispatch = useAppDispatch();

  useEffect(() => {
    if (typeof window !== "undefined") {
      dispatch(fetchAnalogeEingaengeThunk());
      const interval = setInterval(() => {
        dispatch(fetchAnalogeEingaengeThunk());
      }, 10000);
      return () => clearInterval(interval);
    }
  }, [dispatch]);

  return (
    <div className="flex flex-col gap-3 p-4 h-[calc(100vh-13vh-8vh)]">
      <div className="container mx-auto">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="bg-white  rounded-lg p-4 ">
            <h2 className="text-xl font-semibold mb-4 text-gray-700">
              Messwerteingänge
            </h2>
            <AnalogeEingaengeTabelle
              setSelectedId={setSelectedId}
              setSelectedInput={setSelectedInput}
              setIsSettingsModalOpen={setIsSettingsModalOpen}
            />
          </div>

          <div className="bg-white shadow-lg rounded-lg p-4 border border-gray-200 ">
            <h2 className="text-xl font-semibold mb-4 text-gray-700">
              Messkurve Messwerteingang {selectedId ?? "–"}
            </h2>
            <AnalogInputsChart selectedId={selectedId} />
          </div>
        </div>
      </div>

      <AnalogInputsSettingsModal
        selectedInput={selectedInput}
        isOpen={isSettingsModalOpen}
        onClose={() => setIsSettingsModalOpen(false)}
      />
    </div>
  );
}

export default AnalogeEingaenge;
