// 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";

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

  const [selectedKey, setSelectedKey] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);

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

  const labels = history.map((h) => new Date(h.time).toLocaleTimeString());

  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} />
      <DetailModal
        isOpen={isModalOpen}
        selectedKey={selectedKey}
        history={history}
        onClose={handleCloseDetail}
      />
    </div>
  );
};

export default SystemPage;
