"use client";

import React, { useEffect, useRef } from "react";
import { useSelector } from "react-redux";
import { RootState } from "../../../../../../redux/store";
import {
  Chart as ChartJS,
  LineElement,
  PointElement,
  LinearScale,
  TimeScale,
  Title,
  Tooltip,
  Legend,
  Filler,
} from "chart.js";
import zoomPlugin from "chartjs-plugin-zoom";
import "chartjs-adapter-date-fns";

ChartJS.register(
  LineElement,
  PointElement,
  LinearScale,
  TimeScale,
  Title,
  Tooltip,
  Legend,
  Filler,
  zoomPlugin
);

const LoopMeasurementChart = () => {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const chartInstance = useRef<ChartJS | null>(null);

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

  useEffect(() => {
    if (!canvasRef.current) return;
    const ctx = canvasRef.current.getContext("2d");
    if (!ctx) return;

    const chartData = {
      labels: loopMeasurementCurveChartData
        .map((entry) => new Date(entry.t))
        .reverse(),
      datasets: [
        {
          label: "Messwert Minimum",
          data: loopMeasurementCurveChartData.map((e) => e.i).reverse(),
          borderColor: "lightgrey",
          borderWidth: 1,
          fill: false,
          pointRadius: 0,
        },
        {
          label: "Messwert Maximum",
          data: loopMeasurementCurveChartData.map((e) => e.a).reverse(),
          borderColor: "lightgrey",
          borderWidth: 1,
          fill: false,
          pointRadius: 0,
        },
        selectedMode === "DIA0"
          ? {
              label: "Messwert",
              data: loopMeasurementCurveChartData.map((e) => e.m).reverse(),
              borderColor: "#00AEEF",
              borderWidth: 2,
              fill: false,
              pointRadius: 2,
            }
          : {
              label: "Messwert Durchschnitt",
              data: loopMeasurementCurveChartData.map((e) => e.g).reverse(),
              borderColor: "#00AEEF",
              borderWidth: 2,
              fill: false,
              pointRadius: 2,
            },
      ],
    };

    const options = {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: "top" as const,
        },
        tooltip: {
          mode: "index" as const,
          intersect: false,
        },
        zoom: {
          pan: {
            enabled: true,
            mode: "x",
          },
          zoom: {
            wheel: {
              enabled: true,
            },
            pinch: {
              enabled: true,
            },
            mode: "x",
          },
        },
      },
      scales: {
        x: {
          type: "time" as const,
          time: {
            unit: "day",
            tooltipFormat: "dd.MM.yyyy HH:mm",
          },
          title: {
            display: true,
            text: "Zeit",
          },
        },
        y: {
          title: {
            display: true,
            text: unit,
          },
          ticks: {
            precision: 0,
          },
        },
      },
    };

    if (chartInstance.current) {
      chartInstance.current.destroy();
    }

    chartInstance.current = new ChartJS(ctx, {
      type: "line",
      data: chartData,
      options,
    });

    // Kein Cleanup mit Destroy, damit Zoom erhalten bleibt
  }, [loopMeasurementCurveChartData, selectedMode]);

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

export default LoopMeasurementChart;
