"use client";
// components/main/analogInputs/AnalogInputsView.tsx
import React, { useState, useEffect } from "react";
import AnalogInputsTable from "@/components/main/analogInputs/AnalogInputsTable";
import AnalogInputsChart from "@/components/main/analogInputs/AnalogInputsChart";
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 selectedInput = useSelector(
    (state: RootState) => state.selectedAnalogInput
  );
  const selectedId = useSelector(
    (state: RootState) => state.analogInputsHistory.selectedId
  );
  const isSettingsModalOpen = useSelector(
    (state: RootState) => state.analogInputsUi.isSettingsModalOpen
  );

  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 gap-3 p-4 h-[calc(100vh-13vh-8vh)]">
      <div className="container mx-auto">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="bg-white rounded-lg p-4">
            <h2 className="text-xl font-semibold mb-4 text-gray-700">
              Messwerteingänge
            </h2>
            <AnalogInputsTable />
          </div>

          <div className="bg-white shadow-lg rounded-lg p-4 border border-gray-200">
            <h2 className="text-xl font-semibold mb-4 text-gray-700">
              Messkurve Messwerteingang {selectedId ?? "–"}
            </h2>
            <AnalogInputsChart selectedId={selectedId} />
          </div>
        </div>
      </div>

      {selectedInput !== null && <AnalogInputsSettingsModal />}
    </div>
  );
}

export default AnalogInputsView;
