// pages/system.tsx
"use client";
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "../redux/store";
import { getSystemVoltTempThunk } from "../redux/thunks/getSystemVoltTempThunk";
import { SystemOverviewGrid } from "@/components/main/system/SystemOverviewGrid";
import { SystemCharts } from "@/components/main/system/SystemCharts";
import { DetailModal } from "@/components/main/system/DetailModal";
import type { HistoryEntry } from "@/components/main/system/SystemCharts";
import { getSystemspannung5VplusThunk } from "@/redux/thunks/getSystemspannung5VplusThunk";

const SystemPage = () => {
  const dispatch = useDispatch<AppDispatch>();
  const voltages = useSelector(
    (state: RootState) => state.systemVoltTemp.voltages
  );

  const history = useSelector(
    (state: RootState) => state.systemVoltTemp.history
  ) as HistoryEntry[];

  const [selectedKey, setSelectedKey] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [zeitraum, setZeitraum] = useState<"DIA0" | "DIA1" | "DIA2">("DIA1");

  useEffect(() => {
    dispatch(getSystemVoltTempThunk());

    const interval = setInterval(() => {
      dispatch(getSystemVoltTempThunk());
    }, 5000);
    return () => clearInterval(interval);
  }, [dispatch]);

  useEffect(() => {
    dispatch(getSystemspannung5VplusThunk(zeitraum));
  }, [dispatch, zeitraum]);

  const handleOpenDetail = (key: string) => {
    setSelectedKey(key);
    setIsModalOpen(true);
  };

  const handleCloseDetail = () => {
    setSelectedKey(null);
    setIsModalOpen(false);
  };

  return (
    <div className="p-4">
      <h1 className="text-xl font-bold mb-4">
        System Spannungen & Temperaturen
      </h1>
      <SystemOverviewGrid voltages={voltages} onOpenDetail={handleOpenDetail} />
      <SystemCharts history={history} zeitraum={zeitraum} />
      <DetailModal
        isOpen={isModalOpen}
        selectedKey={selectedKey}
        onClose={handleCloseDetail}
        zeitraum={zeitraum}
        setZeitraum={setZeitraum}
      />
    </div>
  );
};

export default SystemPage;
