"use client";
// components/main/analogInputs/AnalogInputsView.tsx
import React, { useState, useEffect } from "react";
import AnalogInputsTable from "@/components/main/analogInputs/AnalogInputsTable";
import AnalogInputsChartModal from "@/components/main/analogInputs/AnalogInputsChartModal";
import AnalogInputsSettingsModal from "@/components/main/analogInputs/AnalogInputsSettingsModal";
import { getAnalogInputsThunk } from "@/redux/thunks/getAnalogInputsThunk";
import { useAppDispatch } from "@/redux/store";
import { useSelector } from "react-redux";
import { RootState } from "@/redux/store";

function AnalogInputsView() {
  const [loading, setLoading] = useState(false); // Add loading state

  const selectedInput = useSelector(
    (state: RootState) => state.selectedAnalogInput
  );
  // selectedId is now displayed within the modal header

  const dispatch = useAppDispatch();

  useEffect(() => {
    if (typeof window !== "undefined") {
      dispatch(getAnalogInputsThunk());
      const interval = setInterval(() => {
        dispatch(getAnalogInputsThunk());
      }, 10000);
      return () => clearInterval(interval);
    }
  }, [dispatch]);

  return (
    <div
      className={`flex flex-col justify-start gap-3 p-4 h-[calc(100vh-13vh-8vh)] ${
        loading ? "cursor-wait" : ""
      }`}
    >
      <div className="container mx-auto">
        <div className="grid grid-cols-1 gap-4 justify-items-start">
          <div className="bg-white rounded-lg p-4 max-w-3xl">
            <h2 className="text-xl font-semibold mb-4 text-gray-700">
              Messwerteingänge
            </h2>
            <AnalogInputsTable loading={loading} />
          </div>
        </div>
      </div>

      {selectedInput !== null && <AnalogInputsSettingsModal />}
      {/* Chart Modal */}
      <AnalogInputsChartModal loading={loading} setLoading={setLoading} />
    </div>
  );
}

export default AnalogInputsView;
