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

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

import { getDigitalInputsThunk } from "@/redux/thunks/getDigitalInputsThunk";
import { getDigitalOutputsThunk } from "../redux/thunks/getDigitalOutputsThunk";

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

const EinAusgaenge: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>();
  const digitalInputs = useSelector(
    (state: RootState) => state.digitalInputsSlice.inputs
  );
  const digitalOutputs = useSelector(
    (state: RootState) => state.digitalOutputsSlice.outputs
  );

  const [selectedInput, setSelectedInput] = useState(null);
  const [selectedOutput, setSelectedOutput] = useState(null);
  const [isInputModalOpen, setIsInputModalOpen] = useState(false);
  const [isOutputModalOpen, setIsOutputModalOpen] = useState(false);

  useEffect(() => {
    dispatch(getDigitalInputsThunk());
    dispatch(getDigitalOutputsThunk());

    const interval = setInterval(() => {
      dispatch(getDigitalInputsThunk());
      dispatch(getDigitalOutputsThunk());
    }, 10000);

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

  const openInputModal = (input: any) => {
    setSelectedInput(input);
    setIsInputModalOpen(true);
  };

  const closeInputModal = () => {
    setSelectedInput(null);
    setIsInputModalOpen(false);
  };

  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">Meldungseingänge</h1>

      <div className="grid grid-cols-1 xl:grid-cols-3 gap-4 items-start ">
        <DigitalInputs
          openInputModal={openInputModal}
          inputRange={{ start: 0, end: 16 }}
        />
        <DigitalInputs
          openInputModal={openInputModal}
          inputRange={{ start: 16, end: 32 }}
        />
      </div>

      {isInputModalOpen && selectedInput && (
        <InputModal
          selectedInput={selectedInput}
          closeInputModal={closeInputModal}
          isOpen={isInputModalOpen}
        />
      )}
    </div>
  );
};

export default EinAusgaenge;
