// components/main/system/SystemCharts.tsx

import React from "react";
import { Line } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js";

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);

export type HistoryEntry = {
  time: string | number | Date;
  "+5V": number;
  "+15V": number;
  "-15V": number;
  "-98V": number;
  "ADC Temp": number;
  "CPU Temp": number;
};

type Props = {
  history: HistoryEntry[];
  zeitraum: "DIA0" | "DIA1" | "DIA2";
};
export const SystemCharts = ({ history }: Props) => {
  const [isLoading, setIsLoading] = React.useState(true);
  const reversedHistory = [...history].reverse();
  const labels = reversedHistory.map((h) =>
    new Date(h.time).toLocaleTimeString()
  );

  const formatValue = (v: number) => v.toFixed(2);

  // Chart.js animation callback
  const animation = {
    onComplete: () => {
      setIsLoading(false);
    },
  };

  React.useEffect(() => {
    setIsLoading(true);
  }, [history]);

  const baseOptions = {
    responsive: true,
    maintainAspectRatio: false,
    animation,
    scales: {
      y: {
        beginAtZero: false,
        grid: { color: "rgba(200,200,200,0.2)" },
        title: { display: true, text: "Wert" },
      },
      x: {
        grid: { color: "rgba(200,200,200,0.2)" },
        title: { display: true, text: "Zeit" },
      },
    },
    plugins: {
      legend: { position: "bottom" as const },
    },
  };

  return (
    <div
      className={`grid grid-cols-1 xl:grid-cols-2 gap-8 ${
        isLoading ? "cursor-wait" : ""
      }`}
    >
      <div className="h-[300px]">
        <Line
          data={{
            labels,
            datasets: [
              {
                label: "+5V",
                data: history.map((h) => formatValue(h["+5V"])),
                borderColor: "rgba(59,130,246,1)",
                backgroundColor: "rgba(59,130,246,0.5)",
                fill: false,
              },
              {
                label: "+15V",
                data: history.map((h) => formatValue(h["+15V"])),
                borderColor: "rgba(34,197,94,1)",
                backgroundColor: "rgba(34,197,94,0.5)",
                fill: false,
              },
              {
                label: "-15V",
                data: history.map((h) => formatValue(h["-15V"])),
                borderColor: "rgba(239,68,68,1)",
                backgroundColor: "rgba(239,68,68,0.5)",
                fill: false,
              },
              {
                label: "-98V",
                data: history.map((h) => formatValue(h["-98V"])),
                borderColor: "rgba(234,179,8,1)",
                backgroundColor: "rgba(234,179,8,0.5)",
                fill: false,
              },
            ],
          }}
          options={{
            ...baseOptions,
            scales: {
              ...baseOptions.scales,
              y: {
                ...baseOptions.scales.y,
                title: {
                  display: true,
                  text: "Spannung (V)", // 👉 Einheit hinzugefügt
                },
              },
            },
            plugins: {
              ...baseOptions.plugins,
              title: { display: true, text: "Systemspannungen" },
            },
          }}
        />
      </div>

      <div className="h-[300px]">
        <Line
          data={{
            labels,
            datasets: [
              {
                label: "ADC Temp",
                data: history.map((h) => h["ADC Temp"]),
                borderColor: "rgba(168,85,247,1)",
                backgroundColor: "rgba(168,85,247,0.5)",
                fill: false,
              },
              {
                label: "CPU Temp",
                data: history.map((h) =>
                  parseFloat(formatValue(h["CPU Temp"]))
                ),
                borderColor: "rgba(251,191,36,1)",
                backgroundColor: "rgba(251,191,36,0.5)",
                fill: false,
              },
            ],
          }}
          options={{
            ...baseOptions,
            scales: {
              ...baseOptions.scales,
              y: {
                ...baseOptions.scales.y,
                title: {
                  display: true,
                  text: "Temperatur (°C)", // 👉 Einheit hinzugefügt
                },
              },
            },
            plugins: {
              ...baseOptions.plugins,
              title: { display: true, text: "Systemtemperaturen" },
            },
          }}
        />
      </div>
    </div>
  );
};
