// components/main/kabelueberwachung/kue705FO/Charts/LoopMeasurementChart/LoopMeasurementChart.tsx
import React, { useEffect, useRef } from "react";
import { useSelector } from "react-redux";
import Chart from "chart.js/auto";
import "chartjs-adapter-moment";

const LoopMeasurementChart = () => {
  const chartRef = useRef<HTMLCanvasElement>(null);
  const chartInstance = useRef<Chart | null>(null);

  // Daten aus Redux abrufen
  const chartData =
    useSelector(
      (state: { chartData: { data: any[] } }) => state.chartData.data
    ) ?? [];

  // Ermittlung des ausgewählten Modus (DIA0, DIA1, DIA2)
  const selectedMode = useSelector(
    (state: { chartMode: { mode: "DIA0" | "DIA1" | "DIA2" } }) =>
      state.chartMode?.mode ?? "DIA0"
  );

  useEffect(() => {
    if (chartRef.current) {
      if (chartInstance.current) {
        chartInstance.current.destroy();
      }

      console.log("Chart Data:", chartData);

      // Datenvorbereitung: Konvertieren der Zeitstempel in Millisekunden
      const processedData = chartData.map((entry) => ({
        ...entry,
        timestampMs: new Date(entry.t).getTime(),
      }));

      // Basis-Datasets für i und a (immer vorhanden)
      const datasets = [
        {
          label: "Messwert Minimum (kOhm)",
          data: processedData.map((entry) => ({
            x: entry.timestampMs,
            y: entry.i,
          })),
          borderColor: "rgba(75, 192, 192, 1)",
          backgroundColor: "rgba(75, 192, 192, 0.2)",
          fill: false,
        },
        {
          label: "Messwert Maximum (kOhm)",
          data: processedData.map((entry) => ({
            x: entry.timestampMs,
            y: entry.a,
          })),
          borderColor: "rgba(192, 75, 75, 1)",
          backgroundColor: "rgba(192, 75, 75, 0.2)",
          fill: false,
        },
      ];

      // Falls `m` vorhanden ist (DIA0), wird es gezeichnet
      if (
        selectedMode === "DIA0" &&
        processedData.some((entry) => entry.m !== undefined)
      ) {
        datasets.push({
          label: "Messwert Mittelwert",
          data: processedData.map((entry) => ({
            x: entry.timestampMs,
            y: entry.m ?? NaN, // Falls `m` nicht existiert, wird `NaN` gesetzt
          })),
          borderColor: "rgba(255, 165, 0, 1)", // Orange
          backgroundColor: "rgba(255, 165, 0, 0.2)",
          fill: false,
        });
      }

      // Falls `g` vorhanden ist (DIA1/DIA2), wird es gezeichnet
      else if (
        selectedMode !== "DIA1" &&
        processedData.some((entry) => entry.g !== undefined)
      ) {
        datasets.push({
          label: "Messwert Durchschnitt",
          data: processedData.map((entry) => ({
            x: entry.timestampMs,
            y: entry.g ?? NaN, // Falls `g` nicht existiert, wird `NaN` gesetzt
          })),
          borderColor: "rgba(75, 75, 192, 1)", // Blau
          backgroundColor: "rgba(75, 75, 192, 0.2)",
          fill: false,
        });
      } else if (
        selectedMode !== "DIA2" &&
        processedData.some((entry) => entry.g !== undefined)
      ) {
        datasets.push({
          label: "Messwert Durchschnitt (g)",
          data: processedData.map((entry) => ({
            x: entry.timestampMs,
            y: entry.g ?? NaN, // Falls `g` nicht existiert, wird `NaN` gesetzt
          })),
          borderColor: "rgba(75, 75, 192, 1)", // Blau
          backgroundColor: "rgba(75, 75, 192, 0.2)",
          fill: false,
        });
      }

      const ctx = chartRef.current.getContext("2d");
      if (ctx) {
        chartInstance.current = new Chart(ctx, {
          type: "line",
          data: { datasets },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            elements: {
              line: {
                spanGaps: true, // Ermöglicht das Zeichnen von Lücken
              },
            },
            scales: {
              x: {
                type: "time",
                time: {
                  unit: "minute",
                  tooltipFormat: "dd.MM.yyyy HH:mm",
                  displayFormats: {
                    minute: "dd.MM.yyyy HH:mm",
                    hour: "dd.MM.yyyy HH:mm",
                    day: "dd.MM.yyyy",
                  },
                },
                title: {
                  display: true,
                  text: "Zeit (Datum & Uhrzeit)",
                },
                ticks: {
                  autoSkip: false,
                  maxRotation: 45,
                  minRotation: 45,
                  callback: function (value, index, values) {
                    const date = new Date(value);
                    return `${date.getDate().toString().padStart(2, "0")}.${(
                      date.getMonth() + 1
                    )
                      .toString()
                      .padStart(2, "0")}.${date.getFullYear()} ${date
                      .getHours()
                      .toString()
                      .padStart(2, "0")}:${date
                      .getMinutes()
                      .toString()
                      .padStart(2, "0")}`;
                  },
                },
              },
              y: {
                ticks: {
                  callback: function (value) {
                    return value.toFixed(2); // Y-Achse Werte mit zwei Dezimalstellen anzeigen
                  },
                },
              },
            },
            plugins: {
              tooltip: {
                callbacks: {
                  label: function (tooltipItem) {
                    let label = tooltipItem.dataset.label || "";
                    if (label) {
                      label += ": ";
                    }
                    if (tooltipItem.raw !== null) {
                      label +=
                        parseFloat(tooltipItem.raw.y).toFixed(2) + " kOhm"; // Dezimalstellen im Tooltip
                    }
                    return label;
                  },
                },
              },
            },
          },
        });
      }
    }
  }, [chartData, selectedMode]);

  return (
    <div style={{ position: "relative", width: "100%", height: "400px" }}>
      <canvas ref={chartRef} />
    </div>
  );
};

export default LoopMeasurementChart;
