// /components/modules/kue705FO/charts/ChartSwitcher.tsx
import React from "react";
import ReactModal from "react-modal";
import LoopChartActionBar from "./LoopMeasurementChart/LoopChartActionBar";
import TDRChartActionBar from "./TDRChart/TDRChartActionBar";
import LoopMeasurementChart from "./LoopMeasurementChart/LoopMeasurementChart";
import TDRChart from "./TDRChart/TDRChart";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "../../../../../redux/store";
import { setChartOpen } from "../../../../../redux/slices/kabelueberwachungChartSlice";

interface ChartSwitcherProps {
  isOpen: boolean;
  onClose: () => void;
}

const ChartSwitcher: React.FC<ChartSwitcherProps> = ({ isOpen, onClose }) => {
  const dispatch = useDispatch();
  const activeMode = useSelector(
    (state: RootState) => state.chartData.activeMode
  );

  // **Neue Funktion: Modal schließen + Redux-Status zurücksetzen**
  const handleClose = () => {
    dispatch(setChartOpen(false)); // Schalter zurücksetzen
    onClose(); // Originale Schließen-Funktion aufrufen
  };

  return (
    <ReactModal
      isOpen={isOpen}
      onRequestClose={handleClose} // Hier `handleClose` statt `onClose`
      ariaHideApp={false}
      style={{
        overlay: { backgroundColor: "rgba(0, 0, 0, 0.5)" },
        content: {
          top: "50%",
          left: "50%",
          bottom: "auto",
          marginRight: "-50%",
          transform: "translate(-50%, -50%)",
          width: "100%",
          maxWidth: "70rem",
          height: "35rem",
          padding: "1rem",
        },
      }}
    >
      <button
        onClick={handleClose} // Hier `handleClose` statt `onClose`
        style={{
          position: "absolute",
          top: "0.625rem",
          right: "0.625rem",
          background: "transparent",
          border: "none",
          fontSize: "1.5rem",
          cursor: "pointer",
        }}
      >
        <i className="bi bi-x-circle-fill"></i>
      </button>

      {/* Nur die richtige ActionBar und das richtige Chart basierend auf dem Modus anzeigen */}
      {activeMode === "Schleife" ? (
        <>
          <h3 className="text-lg font-semibold">Schleifenmessung</h3>
          <LoopChartActionBar />
          <LoopMeasurementChart />
        </>
      ) : (
        <>
          <h3 className="text-lg font-semibold">TDR-Messung</h3>
          <TDRChartActionBar />
          <TDRChart />
        </>
      )}
    </ReactModal>
  );
};

export default ChartSwitcher;
