// components/main/kabelueberwachung/kue705FO/Charts/TDRChart/TDRChart.tsx
"use client";

import React, { useEffect, useRef } from "react";
import { RootState } from "../../../../../../redux/store";
import { useSelector } from "react-redux";
import { Chart, registerables } from "chart.js";
import "chartjs-adapter-date-fns";
import { getColor } from "../../../../../../utils/colors";

const TDRChart: React.FC<{ isFullScreen: boolean }> = ({ isFullScreen }) => {
  const chartRef = useRef<HTMLCanvasElement>(null);
  const chartInstance = useRef<Chart | null>(null);

  // 🟢 **Hole den ausgewählten Slot und Messkurve aus Redux**
  const selectedSlot = useSelector(
    (state: RootState) => state.kueChartMode.selectedSlot
  );
  const selectedChartType = useSelector(
    (state: RootState) => state.kueChartMode.activeMode
  );
  const tdrChartData = useSelector((state: RootState) =>
    selectedSlot !== null ? state.tdrChart.data[selectedSlot] || [] : []
  );

  useEffect(() => {
    import("chartjs-plugin-zoom").then((zoomPlugin) => {
      Chart.register(...registerables, zoomPlugin.default);

      if (chartRef.current && tdrChartData.length > 0) {
        if (chartInstance.current) {
          chartInstance.current.destroy();
        }

        const ctx = chartRef.current.getContext("2d");
        if (ctx) {
          chartInstance.current = new Chart(ctx, {
            type: "line",
            data: {
              datasets: [
                {
                  label: `Modul ${
                    selectedSlot !== null ? selectedSlot + 1 : "?"
                  }`,
                  data: tdrChartData,
                  borderColor: getColor("littwin-blue"),
                  borderWidth: 1,
                  tension: 0.1,
                  parsing: {
                    xAxisKey: "t",
                    yAxisKey: "m",
                  },
                },
              ],
            },
            options: {
              responsive: true,
              maintainAspectRatio: false,
              scales: {
                x: {
                  type: "linear",
                  title: {
                    display: true,
                    text: "Entfernung (m)",
                  },
                },
                y: {
                  title: {
                    display: true,
                    text: "Pegel",
                  },
                },
              },
              plugins: {
                tooltip: {
                  callbacks: {
                    label: function (context) {
                      const rawData = context.raw as { m: number };
                      return `${rawData.m.toFixed(0)}`; // Nur den Wert anzeigen, ohne Icon und Modulnummer
                    },
                  },
                },
                zoom: {
                  pan: {
                    enabled: true,
                    mode: "xy",
                  },
                  zoom: {
                    wheel: {
                      enabled: true,
                    },
                    pinch: {
                      enabled: true,
                    },
                    mode: "xy",
                  },
                },
              },
            },
          });
        }
      }
    });
  }, [JSON.stringify(tdrChartData), selectedSlot, selectedChartType]);

  return (
    <div style={{ width: "100%", height: isFullScreen ? "90%" : "28rem" }}>
      <canvas ref={chartRef} style={{ width: "100%", height: "100%" }} />
    </div>
  );
};

export default TDRChart;
