import React, { useEffect, useRef } from "react";
import ReactModal from "react-modal";
import { useSelector } from "react-redux";
import { RootState } from "../../../../redux/store";
import Chart from "chart.js/auto";
import "chartjs-adapter-date-fns";
import { parseISO } from "date-fns";
import LoopTDRPopup from "../../../modales/kueModal/LoopTDRChartActionBar";

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

const ChartModal: React.FC<ChartModalProps> = ({ isOpen, onClose }) => {
  const chartRef = useRef<HTMLCanvasElement>(null);
  const chartInstance = useRef<Chart | null>(null);

  // Redux State abrufen
  const chartData = useSelector((state: RootState) => state.chartData.data);
  const activeMode = useSelector(
    (state: RootState) => state.chartData.activeMode
  );

  useEffect(() => {
    if (chartRef.current && chartData.length > 0) {
      if (chartInstance.current) {
        chartInstance.current.destroy();
      }

      const ctx = chartRef.current.getContext("2d");
      if (ctx) {
        const labels = chartData.map((entry) =>
          entry.timestamp ? parseISO(entry.timestamp) : new Date()
        );

        chartInstance.current = new Chart(ctx, {
          type: "line",
          data: {
            labels,
            datasets: [
              {
                label: "Isolationswiderstand (MOhm)",
                data: chartData.map((entry) => entry.isolation ?? 0),
                borderColor: "rgba(0, 123, 255, 1)",
                backgroundColor: "rgba(0, 123, 255, 0.2)",
                tension: 0.1,
                yAxisID: "y-left",
              },
              {
                label: "Schleifenwiderstand (kOhm)",
                data: chartData.map((entry) => entry.loop ?? 0),
                borderColor: "rgba(108, 117, 125, 1)",
                backgroundColor: "rgba(108, 117, 125, 0.2)",
                tension: 0.1,
                yAxisID: "y-right",
              },
            ],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
              x: {
                type: "time",
                time: {
                  unit: "hour",
                  tooltipFormat: "dd.MM.yyyy HH:mm",
                },
                title: {
                  display: true,
                  text: "Zeit",
                },
                grid: {
                  drawBorder: true, // 🔥 Stellt sicher, dass die X-Achse sichtbar ist
                },
              },
              y: {
                id: "y-left",
                position: "left",
                title: {
                  display: true,
                  text: "MOhm",
                },
                min: 0,
                max:
                  Math.max(...chartData.map((entry) => entry.isolation ?? 1)) +
                  10,
                grid: {
                  drawOnChartArea: true, // 🔥 Korrektur, damit es sich nicht überlagert
                },
              },
              "y-right": {
                id: "y-right",
                position: "right",
                title: {
                  display: true,
                  text: "kOhm",
                },
                min: 0,
                max: Math.max(...chartData.map((entry) => entry.loop ?? 1)) + 1,
                grid: {
                  drawOnChartArea: false, // 🔥 Verhindert doppelte Linien
                },
              },
            },
          },
        });
      }
    }

    return () => {
      if (chartInstance.current) {
        chartInstance.current.destroy();
        chartInstance.current = null;
      }
    };
  }, [chartData, activeMode]);

  return (
    <ReactModal
      isOpen={isOpen}
      onRequestClose={onClose}
      ariaHideApp={false}
      style={{
        overlay: { backgroundColor: "rgba(0, 0, 0, 0.5)" },
        content: {
          top: "50%",
          left: "50%",
          right: "auto",
          bottom: "auto",
          marginRight: "-50%",
          transform: "translate(-50%, -50%)",
          width: "80%",
          maxWidth: "50rem",
          height: "30rem",
          padding: "1rem",
          overflow: "hidden",
        },
      }}
    >
      <button
        onClick={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>

      {/* Beibehaltung der UI mit Kalender und Buttons */}
      <div style={{ maxHeight: "100%", overflow: "auto" }}>
        <LoopTDRPopup />
      </div>

      {/* Canvas für das Chart */}
      <canvas
        ref={chartRef}
        style={{ width: "100%", height: "20rem", marginTop: "1rem" }}
      ></canvas>
    </ReactModal>
  );
};

export default ChartModal;
