"use client";
// /components/main/system/DetailModal.tsx
import React, { useEffect, useRef, useState, useCallback } from "react";
import { Line } from "react-chartjs-2";
import { useSelector } from "react-redux";
import { RootState, useAppDispatch } from "@/redux/store";
import { Listbox } from "@headlessui/react";
import { setFullScreen } from "@/redux/slices/kabelueberwachungChartSlice";
import DateRangePicker from "@/components/common/DateRangePicker";
import {
  setVonDatum,
  setBisDatum,
} from "@/redux/slices/kabelueberwachungChartSlice";

// Import Thunks
import { getSystemspannung5VplusThunk } from "@/redux/thunks/getSystemspannung5VplusThunk";
import { getSystemspannung15VplusThunk } from "@/redux/thunks/getSystemspannung15VplusThunk";
import { getSystemspannung15VminusThunk } from "@/redux/thunks/getSystemspannung15VminusThunk";
import { getSystemspannung98VminusThunk } from "@/redux/thunks/getSystemspannung98VminusThunk";
import { getTemperaturAdWandlerThunk } from "@/redux/thunks/getTemperaturAdWandlerThunk";
import { getTemperaturProzessorThunk } from "@/redux/thunks/getTemperaturProzessorThunk";

import {
  Chart as ChartJS,
  LineElement,
  PointElement,
  CategoryScale,
  LinearScale,
  Title,
  Tooltip,
  Legend,
  Filler,
  TimeScale,
} from "chart.js";

import "chartjs-adapter-date-fns";
import { de } from "date-fns/locale";

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

// Tailwind-basierte Farbdefinitionen für Chart.js
const chartColors = {
  gray: {
    line: "#6B7280", // tailwind gray-500
    background: "rgba(107, 114, 128, 0.2)", // tailwind gray-500 mit opacity
  },
  littwinBlue: {
    line: "#00AEEF", // littwin-blue
    background: "rgba(0, 174, 239, 0.2)", // littwin-blue mit opacity
  },
};

type ReduxDataEntry = {
  //Alle DIA0 t,m,i,a , DIA1 und DIA2 t,i,a,g
  t: string; // Zeitstempel
  i: number; // Minimum
  a: number; // Maximum
  g?: number; // Durchschnitt (optional, falls vorhanden)
  m?: number; // aktueller Messwert (optional, falls vorhanden)
};

const chartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: { position: "top" as const },
    title: {
      display: true,
      text: "Verlauf",
    },
    tooltip: {
      mode: "index" as const,
      intersect: false,
      callbacks: {
        label: function (ctx: any) {
          return `Messwert: ${ctx.parsed.y}`;
        },
        title: function (items: any[]) {
          const date = items[0].parsed.x;
          return `Zeitpunkt: ${new Date(date).toLocaleString("de-DE")}`;
        },
      },
    },
    zoom: {
      pan: { enabled: true, mode: "x" as const },
      zoom: {
        wheel: { enabled: true },
        pinch: { enabled: true },
        mode: "x" as const,
      },
    },
  },
  scales: {
    x: {
      type: "time" as const,
      time: {
        unit: "day" as const,
        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",
      },
    },
  },
};

type Props = {
  isOpen: boolean;
  selectedKey: string | null;
  onClose: () => void;
  zeitraum: "DIA0" | "DIA1" | "DIA2";
  setZeitraum: (typ: "DIA0" | "DIA1" | "DIA2") => void;
};

export const DetailModal = ({
  isOpen,
  selectedKey,
  onClose,
  zeitraum,
  setZeitraum,
}: Props) => {
  // Stable empty reference to avoid React-Redux dev warning about selector returning new [] each call
  const EMPTY_REDUX_DATA: ReadonlyArray<ReduxDataEntry> = Object.freeze([]);
  const chartRef = useRef<any>(null);
  const [chartData, setChartData] = useState<any>({
    datasets: [],
  });
  const [isLoading, setIsLoading] = useState(false);
  const [shouldUpdateChart, setShouldUpdateChart] = useState(false);
  const [forceUpdate, setForceUpdate] = useState(0); // Für periodische UI-Updates

  const reduxData = useSelector((state: RootState) => {
    switch (selectedKey) {
      case "+5V":
        return state.systemspannung5Vplus[zeitraum];
      case "+15V":
        return state.systemspannung15Vplus[zeitraum];
      case "-15V":
        return state.systemspannung15Vminus[zeitraum];
      case "-98V":
        return state.systemspannung98Vminus[zeitraum];
      case "ADC Temp":
        return state.temperaturAdWandler[zeitraum];
      case "CPU Temp":
        return state.temperaturProzessor[zeitraum];
      default:
        return EMPTY_REDUX_DATA;
    }
  }) as ReduxDataEntry[];

  const isFullScreen = useSelector(
    (state: RootState) => state.kabelueberwachungChartSlice.isFullScreen
  );
  const dispatch = useAppDispatch();

  // API-Request beim Klick auf "Daten laden" - memoized für useEffect dependency
  const handleFetchData = useCallback(() => {
    setIsLoading(true);

    // Clear previous chart data
    setChartData({ datasets: [] });

    // Flag setzen, dass Chart nach Datenempfang aktualisiert werden soll
    setShouldUpdateChart(true);

    switch (selectedKey) {
      case "+5V":
        dispatch(getSystemspannung5VplusThunk(zeitraum));
        break;
      case "+15V":
        dispatch(getSystemspannung15VplusThunk(zeitraum));
        break;
      case "-15V":
        dispatch(getSystemspannung15VminusThunk(zeitraum));
        break;
      case "-98V":
        dispatch(getSystemspannung98VminusThunk(zeitraum));
        break;
      case "ADC Temp":
        dispatch(getTemperaturAdWandlerThunk(zeitraum));
        break;
      case "CPU Temp":
        dispatch(getTemperaturProzessorThunk(zeitraum));
        break;
      default:
        break;
    }
  }, [selectedKey, zeitraum, dispatch]);

  // Reset Zeitraum auf DIA0 und Datumswerte wenn Modal geöffnet wird
  useEffect(() => {
    if (isOpen) {
      setZeitraum("DIA0");
      dispatch(setVonDatum(""));
      dispatch(setBisDatum(""));

      // Chart-Daten zurücksetzen beim Öffnen
      setChartData({ datasets: [] });
    }
  }, [isOpen, setZeitraum, dispatch]);

  // Periodische UI-Updates alle 2 Sekunden während Wartezeit
  useEffect(() => {
    if (isOpen && (!chartData.datasets || chartData.datasets.length === 0)) {
      const interval = setInterval(() => {
        setForceUpdate((prev) => prev + 1); // Force re-render für cursor-wait Update
      }, 2000);

      return () => clearInterval(interval);
    }
  }, [isOpen, chartData.datasets]);

  // Automatisches "Daten laden" alle 4 Sekunden, maximal 2 Versuche
  useEffect(() => {
    if (isOpen && (!chartData.datasets || chartData.datasets.length === 0)) {
      let attempts = 0;
      const interval = setInterval(() => {
        if (attempts < 2) {
          console.log("Auto-clicking 'Daten laden' button...");
          handleFetchData();
          attempts++;
        } else {
          clearInterval(interval);
        }
      }, 4000);

      return () => clearInterval(interval);
    }
  }, [isOpen, chartData.datasets, handleFetchData]);

  const toggleFullScreen = () => {
    dispatch(setFullScreen(!isFullScreen));
    setTimeout(() => {
      chartRef.current?.resize();
    }, 50);
  };

  const handleClose = () => {
    dispatch(setFullScreen(false));
    dispatch(setVonDatum(""));
    dispatch(setBisDatum(""));
    onClose();
  };

  useEffect(() => {
    const loadZoomPlugin = async () => {
      if (typeof window !== "undefined") {
        const zoomPlugin = (await import("chartjs-plugin-zoom")).default;
        if (!ChartJS.registry.plugins.get("zoom")) {
          ChartJS.register(zoomPlugin);
        }
      }
    };
    loadZoomPlugin();
  }, []);

  useEffect(() => {
    if (chartRef.current && selectedKey) {
      chartRef.current.options.plugins.title.text = `Verlauf ${selectedKey}`;
      chartRef.current.update("none");
    }
  }, [selectedKey]);

  useEffect(() => {
    if (chartRef.current) {
      chartRef.current.resetZoom();
    }
  }, [zeitraum]);

  // Chart.js animation complete callback to set isLoading false
  useEffect(() => {
    if (chartRef.current && isLoading) {
      const chartInstance = chartRef.current;
      // Save previous callback to restore later
      const prevCallback = chartInstance.options.animation?.onComplete;
      chartInstance.options.animation = {
        ...chartInstance.options.animation,
        onComplete: () => {
          setIsLoading(false);
          if (typeof prevCallback === "function") prevCallback();
        },
      };
      chartInstance.update();
    }
  }, [chartData, isLoading]);

  // Update chart data when Redux data changes (only after button click)
  useEffect(() => {
    if (shouldUpdateChart && reduxData && reduxData.length > 0) {
      console.log("Redux data for chart:", reduxData);

      // Create datasets array for multiple lines
      const datasets = [];

      // Check which data fields are available and create datasets accordingly
      const hasMinimum = reduxData.some(
        (entry) => entry.i !== undefined && entry.i !== null && entry.i !== 0
      );
      const hasMaximum = reduxData.some(
        (entry) => entry.a !== undefined && entry.a !== null
      );
      const hasAverage = reduxData.some(
        (entry) => entry.g !== undefined && entry.g !== null
      );
      const hasCurrent = reduxData.some(
        (entry) => entry.m !== undefined && entry.m !== null
      );

      // Zuerst Hintergrund-Linien (Minimum/Maximum) - grau
      if (hasMinimum) {
        datasets.push({
          label: "Minimum",
          data: reduxData.map((entry) => ({
            x: new Date(entry.t).getTime(),
            y: entry.i || 0,
          })),
          borderColor: chartColors.gray.line,
          backgroundColor: chartColors.gray.background,
          tension: 0.1,
          fill: false,
        });
      }

      if (hasMaximum) {
        datasets.push({
          label: "Maximum",
          data: reduxData.map((entry) => ({
            x: new Date(entry.t).getTime(),
            y: entry.a || 0,
          })),
          borderColor: chartColors.gray.line,
          backgroundColor: chartColors.gray.background,
          tension: 0.1,
          fill: false,
        });
      }

      // Dann Vordergrund-Linien (Durchschnitt/Messwert) - littwin-blue
      if (hasAverage) {
        datasets.push({
          label: "Durchschnitt",
          data: reduxData.map((entry) => ({
            x: new Date(entry.t).getTime(),
            y: entry.g || 0,
          })),
          borderColor: chartColors.littwinBlue.line,
          backgroundColor: chartColors.littwinBlue.background,
          tension: 0.1,
          fill: false,
        });
      }

      if (hasCurrent) {
        datasets.push({
          label: "Messwert",
          data: reduxData.map((entry) => ({
            x: new Date(entry.t).getTime(),
            y: entry.m || 0,
          })),
          borderColor: chartColors.littwinBlue.line,
          backgroundColor: chartColors.littwinBlue.background,
          tension: 0.1,
          fill: false,
        });
      }

      const newChartData = {
        datasets: datasets,
      };

      console.log("Chart datasets:", datasets.length, "lines");
      setChartData(newChartData);
      setShouldUpdateChart(false); // Reset flag
    } else if (shouldUpdateChart && (!reduxData || reduxData.length === 0)) {
      console.log("No Redux data available");
      setChartData({ datasets: [] });
      setShouldUpdateChart(false); // Reset flag
    }
  }, [reduxData, selectedKey, shouldUpdateChart]);

  if (!isOpen || !selectedKey) return null;

  // Prüfen ob Chart Daten haben (für cursor-wait)
  const hasChartData = chartData.datasets && chartData.datasets.length > 0;

  return (
    <div
      className={`fixed inset-0 bg-black bg-opacity-40 flex items-center justify-center z-50 ${
        !hasChartData ? "cursor-wait" : ""
      }`}
    >
      <div
        className={`bg-white p-6 rounded-xl overflow-auto shadow-2xl transition-all duration-300 ${
          isFullScreen ? "w-[95vw] h-[90vh]" : "w-[50%] h-[60%]"
        } ${!hasChartData ? "cursor-wait" : ""}`}
      >
        <div className="relative">
          <h2 className="text-xl font-semibold">
            Detailansicht: {selectedKey}
          </h2>

          <div className="absolute top-0 right-0 flex gap-3">
            <button
              onClick={toggleFullScreen}
              className="text-2xl text-gray-600 hover:text-gray-800"
            >
              <i
                className={
                  isFullScreen
                    ? "bi bi-fullscreen-exit"
                    : "bi bi-arrows-fullscreen"
                }
              ></i>
            </button>

            <button
              onClick={handleClose}
              className="text-2xl text-gray-600 hover:text-gray-800"
            >
              <i className="bi bi-x-circle-fill"></i>
            </button>
          </div>
        </div>

        <div className="flex items-center justify-start gap-4 mb-4 flex-wrap">
          <DateRangePicker />
          <label className="font-medium">Zeitraum:</label>
          <Listbox value={zeitraum} onChange={setZeitraum}>
            <div className="relative w-48">
              <Listbox.Button className="w-full border px-3 py-1 rounded text-left bg-white flex justify-between items-center text-sm">
                <span>
                  {
                    {
                      DIA0: "Alle Messwerte",
                      DIA1: "Stündlich",
                      DIA2: "Täglich",
                    }[zeitraum]
                  }
                </span>
                <svg
                  className="w-5 h-5 text-gray-400"
                  viewBox="0 0 20 20"
                  fill="currentColor"
                >
                  <path
                    fillRule="evenodd"
                    d="M5.23 7.21a.75.75 0 011.06.02L10 10.585l3.71-3.355a.75.75 0 111.02 1.1l-4.25 3.85a.75.75 0 01-1.02 0l-4.25-3.85a.75.75 0 01.02-1.06z"
                    clipRule="evenodd"
                  />
                </svg>
              </Listbox.Button>
              <Listbox.Options className="absolute z-50 mt-1 w-full border rounded bg-white shadow max-h-60 overflow-auto text-sm">
                {["DIA0", "DIA1", "DIA2"].map((option) => (
                  <Listbox.Option
                    key={option}
                    value={option}
                    className={({ selected, active }) =>
                      `px-4 py-1 cursor-pointer ${
                        selected
                          ? "bg-littwin-blue text-white"
                          : active
                          ? "bg-gray-200"
                          : ""
                      }`
                    }
                  >
                    {
                      {
                        DIA0: "Alle Messwerte",
                        DIA1: "Stündlich",
                        DIA2: "Täglich",
                      }[option]
                    }
                  </Listbox.Option>
                ))}
              </Listbox.Options>
            </div>
          </Listbox>
          <button
            onClick={handleFetchData}
            className={`px-4 py-1 bg-littwin-blue text-white rounded text-sm ${
              isLoading ? "cursor-wait" : ""
            }`}
            disabled={isLoading}
          >
            {isLoading ? "Laden..." : "Daten laden"}
          </button>
        </div>

        <div className="h-[85%]">
          <Line ref={chartRef} data={chartData} options={chartOptions} />
        </div>
      </div>
    </div>
  );
};
