"use client";

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

import DigitalOutputsModal from "./DigitalOutputsModal";
import DigitalOutputsWidget from "./DigitalOutputsWidget";

import { getDigitalOutputsThunk } from "@/redux/thunks/getDigitalOutputsThunk";
import type { DigitalOutput } from "@/types/digitalOutput";

const DigitalOutputsView: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>();
  const [selectedOutput, setSelectedOutput] = useState<DigitalOutput | null>(
    null
  );
  const [isOutputModalOpen, setIsOutputModalOpen] = useState(false);

  useEffect(() => {
    // Fetch immediately on mount to ensure data is present without waiting for the first interval
    dispatch(getDigitalOutputsThunk());

    // Then continue polling periodically
    const interval = setInterval(() => {
      dispatch(getDigitalOutputsThunk());
    }, 3000);

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

  const openOutputModal = (output: DigitalOutput) => {
    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">
        <DigitalOutputsWidget openOutputModal={openOutputModal} />
      </div>

      {selectedOutput && (
        <DigitalOutputsModal
          selectedOutput={selectedOutput}
          isOpen={isOutputModalOpen}
          closeOutputModal={closeOutputModal}
        />
      )}
    </div>
  );
};

export default DigitalOutputsView;
