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

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

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

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

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(getDigitalOutputsThunk());

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

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

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

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

export default EinAusgaenge;
