// components/main/digitalInputs/DigitalInputsView.tsx
"use client";

import React, { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { AppDispatch } from "@/redux/store";

import InputModal from "@/components/main/digitalInputs/digitalInputsModal";
import { getDigitalInputsThunk } from "@/redux/thunks/getDigitalInputsThunk";
import DigitalInputsWidget from "@/components/main/digitalInputs/DigitalInputsWidget";

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

  interface DigitalInput {
    id: number;
    eingangOffline: boolean;
    status: boolean;
    label: string;
    [key: string]: unknown;
  }

  const [selectedInput, setSelectedInput] = useState<DigitalInput | null>(null);
  const [isInputModalOpen, setIsInputModalOpen] = useState(false);

  useEffect(() => {
    dispatch(getDigitalInputsThunk());
    const interval = setInterval(() => {
      dispatch(getDigitalInputsThunk());
    }, 10000);
    return () => clearInterval(interval);
  }, [dispatch]);

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

  const closeInputModal = () => {
    setSelectedInput(null);
    setIsInputModalOpen(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 ">
        <DigitalInputsWidget
          openInputModal={openInputModal}
          inputRange={{ start: 0, end: 16 }}
        />
        <DigitalInputsWidget
          openInputModal={openInputModal}
          inputRange={{ start: 16, end: 32 }}
        />
      </div>

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

export default DigitalInputsView;
