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

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

  // Redux-Daten abrufen
  const chartData = useSelector((state: RootState) => state.chartData.data);

  useEffect(() => {
    if (chartRef.current && chartData.length > 0) {
      if (chartInstance.current) {
        chartInstance.current.destroy(); // Bestehendes Chart zerstören
      }

      const ctx = chartRef.current.getContext("2d");
      if (ctx) {
        const labels = chartData.map((entry) =>
          entry.timestamp ? parseISO(entry.timestamp) : new Date()
        );

        chartInstance.current = new Chart(ctx, {
          type: "line",
          data: {
            labels,
            datasets: [
              {
                label: "Schleifenwiderstand (kOhm)",
                data: chartData.map((entry) => entry.loop ?? 0),
                borderColor: "rgba(75, 192, 192, 1)", // Türkis
                backgroundColor: "rgba(75, 192, 192, 0.2)",
                tension: 0.1,
                yAxisID: "y-left",
              },
              {
                label: "Zusätzliche Schleifenmesswerte",
                data: chartData.map((entry) => entry.additional ?? 0),
                borderColor: "rgba(255, 159, 64, 1)", // Orange
                backgroundColor: "rgba(255, 159, 64, 0.2)",
                tension: 0.1,
                yAxisID: "y-right",
              },
            ],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
              x: {
                type: "time",
                time: {
                  unit: "hour",
                  tooltipFormat: "dd.MM.yyyy HH:mm",
                },
                title: {
                  display: true,
                  text: "Zeit",
                },
                grid: {
                  drawBorder: true,
                },
              },
              y: {
                id: "y-left",
                position: "left",
                title: {
                  display: true,
                  text: "kOhm",
                },
                min: 0,
                max: Math.max(...chartData.map((entry) => entry.loop ?? 1)) + 1,
              },
              "y-right": {
                id: "y-right",
                position: "right",
                title: {
                  display: true,
                  text: "Zusätzliche Werte",
                },
                min: 0,
                max:
                  Math.max(...chartData.map((entry) => entry.additional ?? 1)) +
                  1,
                grid: {
                  drawOnChartArea: false,
                },
              },
            },
          },
        });
      }
    }

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

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

export default LoopMeasurementChart;
