"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="grid grid-cols-1 gap-4 justify-items-start">
  <div className="rounded-lg p-4 max-w-3xl text-[var(--color-fg)] bg-[var(--color-surface)] dark:bg-[var(--color-surface)] border border-[var(--color-border)] shadow-sm">
          <h2 className="text-xl font-semibold mb-4 text-[var(--color-fg)] tracking-wide">
            Messwerteingänge
          </h2>
          <AnalogInputsTable loading={loading} />
        </div>
      </div>

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

export default AnalogInputsView;
