"use client"; // IsoChartView.tsx

import React, { useEffect } from "react";
import ReactModal from "react-modal";
import IsoMeasurementChart from "./IsoMeasurementChart";
import IsoChartActionBar, { useIsoDataLoader } from "./IsoChartActionBar";
import Report from "./Report";
import { useSelector, useDispatch } from "react-redux";
import { AppDispatch } from "@/redux/store";
import { RootState } from "@/redux/store";
import {
  setChartOpen,
  setFullScreen,
  setSlotNumber,
  setChartTitle,
} from "@/redux/slices/kabelueberwachungChartSlice";

import { resetBrushRange } from "@/redux/slices/brushSlice";

import {
  setVonDatum,
  setBisDatum,
  setSelectedMode,
  setSelectedSlotType,
} from "@/redux/slices/kabelueberwachungChartSlice";

interface IsoChartViewProps {
  isOpen: boolean;
  onClose: () => void;
  slotIndex: number;
}

const IsoChartView: React.FC<IsoChartViewProps> = ({
  isOpen,
  onClose,
  slotIndex,
}) => {
  const dispatch = useDispatch<AppDispatch>();
  const { loadData } = useIsoDataLoader();

  const { isFullScreen, chartTitle } = useSelector(
    (state: RootState) => state.kabelueberwachungChartSlice
  );

  // **Modal schließen + Redux-Status zurücksetzen**
  const handleClose = () => {
    const today = new Date();
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(today.getDate() - 30);

    const toISO = (date: Date) => date.toLocaleDateString("sv-SE");

    // Reset Datum
    dispatch(setVonDatum(toISO(thirtyDaysAgo)));
    dispatch(setBisDatum(toISO(today)));

    // Reset Dropdowns
    dispatch(setSelectedMode("DIA1"));
    dispatch(setSelectedSlotType("isolationswiderstand"));
    dispatch(setChartTitle("Messkurve")); // Reset zu Messkurve

    // Sonstiges Reset
    dispatch(setChartOpen(false));
    dispatch(setFullScreen(false));
    dispatch(resetBrushRange());

    onClose();
  };

  // **Vollbildmodus umschalten**
  const toggleFullScreen = () => {
    dispatch(setFullScreen(!isFullScreen));
  };

  // Modal öffnen - ISO spezifische Einstellungen
  useEffect(() => {
    if (isOpen) {
      const today = new Date();
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(today.getDate() - 30);

      const toISO = (date: Date) => date.toLocaleDateString("sv-SE");

      // Set slot number first
      dispatch(setSlotNumber(slotIndex));

      // Set dates
      dispatch(setVonDatum(toISO(thirtyDaysAgo)));
      dispatch(setBisDatum(toISO(today)));

      // Set ISO specific settings
      dispatch(setSelectedSlotType("isolationswiderstand"));

      // Set default to Messkurve
      dispatch(setChartTitle("Messkurve"));

      // Automatisch Daten laden nach kurzer Verzögerung
      // um sicherzustellen, dass alle Redux-States gesetzt sind
      const timer = setTimeout(() => {
        loadData();
      }, 100);

      // Cleanup timer
      return () => clearTimeout(timer);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen, slotIndex, dispatch]); // loadData bewusst ausgelassen um Endlosschleife zu vermeiden

  return (
    <ReactModal
      isOpen={isOpen}
      onRequestClose={handleClose}
      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: isFullScreen ? "90vw" : "70rem",
          height: isFullScreen ? "90vh" : "35rem",
          padding: "1rem",
          transition: "all 0.3s ease-in-out",
          display: "flex",
          flexDirection: "column",
        },
      }}
    >
      {/* Action-Buttons */}
      <div
        style={{
          position: "absolute",
          top: "0.625rem",
          right: "0.625rem",
          display: "flex",
          gap: "0.75rem",
        }}
      >
        {/* Fullscreen-Button */}
        <button
          onClick={toggleFullScreen}
          style={{
            background: "transparent",
            border: "none",
            fontSize: "1.5rem",
            cursor: "pointer",
          }}
        >
          <i
            className={
              isFullScreen ? "bi bi-fullscreen-exit" : "bi bi-arrows-fullscreen"
            }
          ></i>
        </button>

        {/* Schließen-Button */}
        <button
          onClick={handleClose}
          style={{
            background: "transparent",
            border: "none",
            fontSize: "1.5rem",
            cursor: "pointer",
          }}
        >
          <i className="bi bi-x-circle-fill"></i>
        </button>
      </div>

      {/* Chart-Container */}
      <div
        style={{
          flex: 1,
          display: "flex",
          flexDirection: "column",
          height: "100%",
        }}
      >
        <h3 className="text-lg font-semibold">
          {chartTitle === "Messkurve" ? "Isolationswiderstand" : "Meldungen"}
        </h3>
        <IsoChartActionBar />
        <div style={{ flex: 1, height: "90%" }}>
          {chartTitle === "Messkurve" ? <IsoMeasurementChart /> : <Report />}
        </div>
      </div>
    </ReactModal>
  );
};

export default IsoChartView;
