"use client"; // components/main/kabelueberwachung/kue705FO/Charts/LoopMeasurementChart/LoopMeasurementChart.tsx
import React, { useEffect, useRef, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "../../../../../../redux/store";
import Chart from "chart.js/auto";
import "chartjs-adapter-moment";
import "chartjs-plugin-zoom";
import {
  setVonDatum,
  setBisDatum,
} from "../../../../../../redux/slices/kabelueberwachungChartSlice";

const LoopMeasurementChart = () => {
  const dispatch = useDispatch();
  const isFullScreen = useSelector(
    (state: RootState) => state.kabelueberwachungChart.isFullScreen
  );
  const { loopMeasurementCurveChartData, vonDatum, bisDatum } = useSelector(
    (state: RootState) => state.kabelueberwachungChart
  );
  const selectedMode = useSelector(
    (state: RootState) => state.kabelueberwachungChart.selectedMode
  );

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

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

      console.log("Chart Data:", loopMeasurementCurveChartData);
      console.log("Von Datum:", vonDatum, "Bis Datum:", bisDatum);
      console.log("Selected Mode:", selectedMode);

      const datasets = [
        {
          label: "Messwert Minimum (kOhm)",
          data: loopMeasurementCurveChartData.map((entry) => ({
            x: new Date(entry.t).getTime(),
            y: entry.i,
          })),
          borderColor: "#17a2b8", // Türkis
          backgroundColor: "rgba(23, 162, 184, 0.2)",
          pointRadius: 2,
          borderWidth: 2,
          fill: false,
        },
        {
          label: "Messwert Maximum (kOhm)",
          data: loopMeasurementCurveChartData.map((entry) => ({
            x: new Date(entry.t).getTime(),
            y: entry.a,
          })),
          borderColor: "#dc3545", // Rot
          backgroundColor: "rgba(220, 53, 69, 0.2)",
          pointRadius: 2,
          borderWidth: 2,
          fill: false,
        },
        {
          label: "Messwert Aktuell (m)",
          data: loopMeasurementCurveChartData.map((entry) => ({
            x: new Date(entry.t).getTime(),
            y: entry.m ?? NaN,
          })),
          borderColor: "#ffc107", // Gelb
          backgroundColor: "rgba(255, 193, 7, 0.2)",
          pointRadius: 2,
          borderWidth: 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 },
            },
            scales: {
              x: {
                type: "time",
                time: {
                  unit: "day",
                  tooltipFormat: "dd.MM.yyyy HH:mm",
                  displayFormats: { day: "dd.MM.yyyy" },
                },
                title: { display: true, text: "Zeit (Datum)" },
                min: new Date(vonDatum).getTime(),
                max: new Date(bisDatum).getTime(),
              },
              y: {
                title: { display: true, text: "Messwert (kOhm)" },
                ticks: {
                  callback: (value) =>
                    (typeof value === "number" ? value.toFixed(2) : value) +
                    " kOhm",
                },
              },
            },
            plugins: {
              tooltip: {
                callbacks: {
                  label: (tooltipItem) => {
                    const rawItem = tooltipItem.raw as { x: number; y: number };
                    return `${tooltipItem.dataset.label}: ${rawItem.y.toFixed(
                      2
                    )} kOhm`;
                  },
                },
              },
              zoom: {
                pan: {
                  enabled: true,
                  mode: "xy",
                },
                zoom: {
                  wheel: { enabled: true },
                  pinch: { enabled: true },
                  mode: "xy",
                  onZoom: ({ chart }) => {
                    const xScale = chart.scales.x;
                    if (xScale.min && xScale.max) {
                      const newVonDatum = new Date(xScale.min)
                        .toISOString()
                        .split("T")[0];
                      const newBisDatum = new Date(xScale.max)
                        .toISOString()
                        .split("T")[0];

                      if (newVonDatum !== vonDatum)
                        dispatch(setVonDatum(newVonDatum));
                      if (newBisDatum !== bisDatum)
                        dispatch(setBisDatum(newBisDatum));
                    }
                  },
                },
              },
            },
          },
        });
      }
    }
  }, [loopMeasurementCurveChartData, vonDatum, bisDatum, selectedMode]);

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

export default LoopMeasurementChart;
