import React, { useEffect, useRef } from "react";
import { useSelector } from "react-redux";
import { RootState } from "../../../../../../redux/store";
import Chart from "chart.js/auto";

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

  const chartData =
    useSelector((state: RootState) => state.chartData.data) ?? [];

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

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

      const ctx = chartRef.current.getContext("2d");
      if (ctx) {
        chartInstance.current = new Chart(ctx, {
          type: "line",
          data: {
            datasets: [
              {
                label: "Messwert i (kOhm)",
                data: processedData.map((entry) => ({
                  x: entry.timestampMs,
                  y: entry.i ?? 0,
                })),
                borderColor: "rgba(75, 192, 192, 1)",
                backgroundColor: "rgba(75, 192, 192, 0.2)",
                fill: true,
              },
              {
                label: "Messwert a (kOhm)",
                data: processedData.map((entry) => ({
                  x: entry.timestampMs,
                  y: entry.a ?? 0,
                })),
                borderColor: "rgba(192, 75, 75, 1)",
                backgroundColor: "rgba(192, 75, 75, 0.2)",
                fill: true,
              },
              {
                label: "Messwert g (kOhm)",
                data: processedData.map((entry) => ({
                  x: entry.timestampMs,
                  y: entry.g ?? 0,
                })),
                borderColor: "rgba(75, 75, 192, 1)",
                backgroundColor: "rgba(75, 75, 192, 0.2)",
                fill: true,
              },
            ],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
              x: {
                type: "linear",
                position: "bottom",
                ticks: {
                  callback: function (value, index, values) {
                    const date = new Date(value);
                    return `${date.getDate()}.${
                      date.getMonth() + 1
                    }.${date.getFullYear()} ${date.getHours()}:${date.getMinutes()}`;
                  },
                },
                title: {
                  display: true,
                  text: "Zeit",
                },
              },
              y: {
                title: {
                  display: true,
                  text: "kOhm",
                },
                min: 0,
                max: 2,
              },
            },
          },
        });
      }
    }

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

  return <canvas ref={chartRef} style={{ width: "100%", height: "20rem" }} />;
};

export default LoopMeasurementChart;
