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);

  // Nutze entweder Redux-Daten oder Mock-Daten
  const chartData = useSelector((state: RootState) => state.chartData.data) || [
    { timestamp: "2025-02-13T12:00:00", loop: 0.8 },
    { timestamp: "2025-02-13T12:10:00", loop: 1.2 },
    { timestamp: "2025-02-13T12:20:00", loop: 1.5 },
  ];

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

      const ctx = chartRef.current.getContext("2d");
      if (ctx) {
        chartInstance.current = new Chart(ctx, {
          type: "line",
          data: {
            labels: chartData.map((entry) => parseISO(entry.timestamp)),
            datasets: [
              {
                label: "Schleifenwiderstand (kOhm)",
                data: chartData.map((entry) => entry.loop ?? 0),
                borderColor: "rgba(0, 123, 255, 1)",
                backgroundColor: "rgba(0, 123, 255, 0.2)",
                tension: 0.1,
              },
            ],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
              x: {
                type: "time",
                time: { unit: "minute", tooltipFormat: "dd.MM.yyyy HH:mm" },
                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;
