"use client"; // /pages/digitalOutputs.tsx
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "../redux/store";

import OutputModal from "../components/main/einausgaenge/modals/OutputModal";

import { fetchDigitaleEingaengeThunk } from "../redux/thunks/fetchDigitaleEingaengeThunk";
import { fetchDigitalOutputsThunk } from "../redux/thunks/fetchDigitalOutputsThunk";

import DigitalOutputs from "../components/main/einausgaenge/DigitalOutputs";

const EinAusgaenge: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>();

  const digitalOutputs = useSelector(
    (state: RootState) => state.digitalOutputsSlice.outputs
  );

  const [selectedOutput, setSelectedOutput] = useState(null);
  const [isOutputModalOpen, setIsOutputModalOpen] = useState(false);

  useEffect(() => {
    dispatch(fetchDigitalOutputsThunk());

    const interval = setInterval(() => {
      dispatch(fetchDigitaleEingaengeThunk());
      dispatch(fetchDigitalOutputsThunk());
    }, 10000);

    return () => clearInterval(interval);
  }, [dispatch]);

  const openOutputModal = (output: any) => {
    setSelectedOutput(output);
    setIsOutputModalOpen(true);
  };

  const closeOutputModal = () => {
    setSelectedOutput(null);
    setIsOutputModalOpen(false);
  };

  return (
    <div className="flex flex-col gap-3 p-4 h-[calc(100vh-13vh-8vh)] laptop:h-[calc(100vh-10vh-5vh)] xl:h-[calc(100vh-10vh-6vh)] laptop:gap-0">
      <h1 className="text-base font-semibold mb-2">Ein- und Ausgänge</h1>

      <div className="grid grid-cols-1 xl:grid-cols-3 gap-4 items-start ">
        <DigitalOutputs openOutputModal={openOutputModal} />
      </div>

      {/* ✅ Modal aktiv einbinden */}
      <OutputModal
        selectedOutput={selectedOutput}
        isOpen={isOutputModalOpen}
        closeOutputModal={closeOutputModal}
      />
    </div>
  );
};

export default EinAusgaenge;
