"use client"; // /components/main/analogeEingaenge/AnalogInputsChart.tsx
import React, { useEffect } from "react";
import { Line } from "react-chartjs-2";
import {
  Chart as ChartJS,
  LineElement,
  PointElement,
  CategoryScale,
  LinearScale,
  Tooltip,
  Legend,
  Filler,
  TimeScale,
} from "chart.js";
import "chartjs-adapter-date-fns";
import { de } from "date-fns/locale";
import { useSelector, useDispatch } from "react-redux";
import type { RootState, AppDispatch } from "../../../redux/store";
import { fetchAnalogInputsHistoryThunk } from "../../../redux/thunks/fetchAnalogInputsHistoryThunk";

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

export default function AnalogInputsChart({
  selectedId,
}: {
  selectedId: number | null;
}) {
  const dispatch = useDispatch<AppDispatch>();
  const { data, isLoading, error } = useSelector(
    (state: RootState) => state.analogInputsHistory
  );

  useEffect(() => {
    dispatch(fetchAnalogInputsHistoryThunk());
  }, [dispatch]);

  if (!selectedId) {
    return <div className="text-gray-500">Bitte einen Eingang auswählen</div>;
  }

  const key = String(selectedId + 99);
  const inputData = data[key];

  if (!inputData) {
    return (
      <div className="text-red-500">
        Keine Verlaufsdaten für Eingang {selectedId} gefunden.
      </div>
    );
  }

  const chartData = {
    datasets: [
      {
        label: `Eingang ${selectedId}`,
        data: inputData.map((point: any) => ({
          x: point.t,
          y: point.m,
        })),
        fill: false,
        borderColor: "#00B0F0",
        backgroundColor: "#00B0F0",
        tension: 0.3,
      },
    ],
  };

  const chartOptions = {
    responsive: true,
    plugins: {
      legend: { position: "top" as const },
      tooltip: { mode: "index" as const, intersect: false },
      title: {
        display: true,
        text: `Verlauf Eingang ${selectedId} – letzte 24 Stunden`,
      },
    },
    scales: {
      x: {
        type: "time" as const,
        time: {
          unit: "hour",
          tooltipFormat: "HH:mm 'Uhr' dd.MM.",
          displayFormats: {
            hour: "HH:mm",
            day: "dd.MM.",
          },
        },
        adapters: {
          date: {
            locale: de,
          },
        },
        title: {
          display: true,
          text: "Zeit ",
        },
      },
      y: {
        title: {
          display: true,
          text: "Messwert",
        },
      },
    },
  };

  return (
    <div className="w-full h-[400px]">
      <Line data={chartData} options={chartOptions} />
    </div>
  );
}
