"use client";
import React, { useEffect, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState, AppDispatch } from "@/redux/store";
import { Line } from "react-chartjs-2";
import {
  Chart as ChartJS,
  LineElement,
  PointElement,
  CategoryScale,
  LinearScale,
  Tooltip,
  Legend,
  Filler,
  TimeScale,
} from "chart.js";
import type { ChartOptions } from "chart.js";
import "chartjs-adapter-date-fns";
import { de } from "date-fns/locale";
import { getAnalogInputsHistoryThunk } from "@/redux/thunks/getAnalogInputsHistoryThunk";
import {
  setVonDatum,
  setBisDatum,
  setZeitraum,
  setAutoLoad,
} from "@/redux/slices/analogInputs/analogInputsHistorySlice";
import DateRangePicker from "@/components/common/DateRangePicker";
import { Listbox } from "@headlessui/react";
import { getColor } from "@/utils/colors";

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

type AnalogInputHistoryPoint = {
  t: string;
  m: number;
};

export default function AnalogInputsChart() {
  const dispatch = useDispatch<AppDispatch>();
  const chartRef = useRef<any>(null);

  const { zeitraum, vonDatum, bisDatum, data, autoLoad, selectedId } =
    useSelector((state: RootState) => state.analogInputsHistory);

  useEffect(() => {
    const today = new Date();
    const vor30Tagen = new Date(today);
    vor30Tagen.setDate(today.getDate() - 30);

    if (!vonDatum) dispatch(setVonDatum(vor30Tagen.toISOString().slice(0, 10)));
    if (!bisDatum) dispatch(setBisDatum(today.toISOString().slice(0, 10)));
  }, [dispatch, vonDatum, bisDatum]);

  const handleFetchChartData = () => {
    if (!selectedId) return;
    dispatch(
      getAnalogInputsHistoryThunk({
        eingang: selectedId,
        zeitraum,
        vonDatum,
        bisDatum,
      })
    );
  };

  const dataKey = selectedId ? String(selectedId + 99) : null;
  const chartData = {
    datasets:
      dataKey && data[dataKey]
        ? [
            {
              label: `Messwerteingang ${selectedId}`,
              data: data[dataKey].map((p: AnalogInputHistoryPoint) => ({
                x: new Date(p.t),
                y: p.m,
              })),
              fill: false,
              borderColor: getColor("littwin-blue"),
              backgroundColor: "rgba(59,130,246,0.3)",
              borderWidth: 2,
              pointRadius: 0,
              tension: 0.1,
            },
          ]
        : [],
  };

  const chartOptions: ChartOptions<"line"> = {
    responsive: true,
    plugins: {
      legend: { position: "top" },
      title: { display: true, text: "Verlauf" },
      tooltip: {
        mode: "index",
        intersect: false,
        callbacks: {
          label: (ctx) => `Messwert: ${ctx.parsed.y}`,
          title: (items) =>
            `Zeitpunkt: ${new Date(items[0].parsed.x).toLocaleString("de-DE")}`,
        },
      },
    },
    scales: {
      x: {
        type: "time",
        time: {
          unit: "day",
          tooltipFormat: "dd.MM.yyyy HH:mm",
          displayFormats: { day: "dd.MM.yyyy" },
        },
        adapters: { date: { locale: de } },
        title: { display: true, text: "Zeit" },
      },
      y: { title: { display: true, text: "Messwert" } },
    },
  };

  useEffect(() => {
    if (autoLoad && selectedId) {
      dispatch(
        getAnalogInputsHistoryThunk({
          eingang: selectedId,
          zeitraum,
          vonDatum,
          bisDatum,
        })
      );
      dispatch(setAutoLoad(false)); // ✅ zurücksetzen, sonst endlose Schleife
    }
  }, [autoLoad, selectedId, dispatch, zeitraum, vonDatum, bisDatum]);
  return (
    <div className="flex flex-col gap-3">
      <div className="flex flex-wrap items-center gap-4 mb-2">
        <DateRangePicker />

        <Listbox value={zeitraum} onChange={(v) => dispatch(setZeitraum(v))}>
          <div className="relative w-48">
            <Listbox.Button className="w-full border px-3 py-1 rounded bg-white flex justify-between items-center text-sm">
              <span>
                {zeitraum === "DIA0"
                  ? "Alle Messwerte"
                  : zeitraum === "DIA1"
                  ? "Stündlich"
                  : "Täglich"}
              </span>
              <i className="bi bi-chevron-down text-gray-400" />
            </Listbox.Button>
            <Listbox.Options className="absolute z-10 mt-1 w-full border bg-white shadow rounded text-sm">
              {["DIA0", "DIA1", "DIA2"].map((option) => (
                <Listbox.Option
                  key={option}
                  value={option}
                  className="px-4 py-1 cursor-pointer hover:bg-gray-200"
                >
                  {option === "DIA0"
                    ? "Alle Messwerte"
                    : option === "DIA1"
                    ? "Stündlich"
                    : "Täglich"}
                </Listbox.Option>
              ))}
            </Listbox.Options>
          </div>
        </Listbox>

        <button
          onClick={handleFetchChartData}
          className="px-4 py-1 bg-littwin-blue text-white rounded text-sm"
        >
          Daten laden
        </button>
      </div>

      <div className="h-[50vh] w-full">
        <Line ref={chartRef} data={chartData} options={chartOptions} />
      </div>
    </div>
  );
}
