"use client";
// /components/main/kabelueberwachung/kue705FO/Charts/LoopMeasurementChart/LoopChartActionBar.tsx
import React from "react";
import DateRangePicker from "./DateRangePicker";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../../../../../redux/store";
import {
  setVonDatum,
  setBisDatum,
  setLoopMeasurementCurveChartData,
  setSelectedMode,
  setSelectedSlotType,
  setChartOpen,
  setFullScreen,
  setLoading,
} from "../../../../../../redux/slices/kabelueberwachungChartSlice";
import { setBrushRange } from "../../../../../../redux/slices/brushSlice";
import { setChartTitle } from "../../../../../../redux/slices/loopChartTypeSlice";
//-----------------------------------------------------------------------------------useLoopChartLoader
export const useLoopChartLoader = () => {
  const dispatch = useDispatch();
  const { vonDatum, bisDatum, selectedMode, selectedSlotType, slotNumber } =
    useSelector((state: RootState) => state.kabelueberwachungChartSlice);

  const formatDate = (dateString: string) => {
    const [year, month, day] = dateString.split("-");
    return `${year};${month};${day}`;
  };

  const getApiUrl = (
    mode: "DIA0" | "DIA1" | "DIA2",
    type: number,
    slotNumber: number
  ) => {
    const typeFolder =
      type === 3 ? "isolationswiderstand" : "schleifenwiderstand";

    if (process.env.NODE_ENV === "development") {
      return `/api/cpl/slotDataAPIHandler?slot=${slotNumber}&messart=${typeFolder}&dia=${mode}&vonDatum=${vonDatum}&bisDatum=${bisDatum}`;
    }

    return `${window.location.origin}/CPL?seite.ACP&${mode}=${formatDate(
      vonDatum
    )};${formatDate(bisDatum)};${slotNumber};${type};`;
  };

  const loadLoopChartData = async () => {
    const type = selectedSlotType === "schleifenwiderstand" ? 4 : 3;
    if (slotNumber === null) return;

    dispatch(setLoading(true));
    dispatch(setChartOpen(false));
    dispatch(setLoopMeasurementCurveChartData([]));

    const startTime = Date.now();
    const MIN_LOADING_TIME_MS = 1000;

    try {
      const apiUrl = getApiUrl(selectedMode, type, slotNumber);
      const response = await fetch(apiUrl);
      const data = await response.json();

      const waitTime = Math.max(
        0,
        MIN_LOADING_TIME_MS - (Date.now() - startTime)
      );
      await new Promise((res) => setTimeout(res, waitTime));

      if (Array.isArray(data) && data.length > 0) {
        dispatch(setLoopMeasurementCurveChartData(data));
        dispatch(setChartOpen(true));
      } else {
        dispatch(setLoopMeasurementCurveChartData([]));
        dispatch(setChartOpen(false));
        alert("⚠️ Keine Daten im gewählten Zeitraum.");
      }
    } catch (err) {
      console.error("❌ Fehler beim Laden:", err);
      alert("❌ Fehler beim Laden.");
    } finally {
      dispatch(setLoading(false));
    }
  };

  return { loadLoopChartData };
};

//-----------------------------------------------------------------------------------LoopChartActionBar
const LoopChartActionBar: React.FC = () => {
  const dispatch = useDispatch();

  const {
    vonDatum,
    bisDatum,
    selectedMode,
    selectedSlotType,
    isChartOpen,
    slotNumber,
    loopMeasurementCurveChartData,
    isLoading,
  } = useSelector((state: RootState) => state.kabelueberwachungChartSlice);

  const getApiUrl = (
    mode: "DIA0" | "DIA1" | "DIA2",
    type: number,
    slotNumber: number
  ) => {
    const typeFolder =
      type === 3 ? "isolationswiderstand" : "schleifenwiderstand";

    const baseUrl =
      process.env.NODE_ENV === "development"
        ? `/api/cpl/slotDataAPIHandler?slot=${slotNumber}&messart=${typeFolder}&dia=${mode}&vonDatum=${vonDatum}&bisDatum=${bisDatum}`
        : `${window.location.origin}/CPL?seite.ACP&${mode}=${formatDate(
            vonDatum
          )};${formatDate(bisDatum)};${slotNumber};${type};`;
    console.log("baseUrl", baseUrl);

    return baseUrl;
  };

  const formatDate = (dateString: string) => {
    const [year, month, day] = dateString.split("-");
    return `${year};${month};${day}`;
  };

  const handleFetchData = async () => {
    const type = selectedSlotType === "schleifenwiderstand" ? 4 : 3;

    if (slotNumber === null) {
      alert("⚠️ Bitte zuerst einen Steckplatz auswählen!");
      return;
    }

    const apiUrl = getApiUrl(selectedMode, type, slotNumber);
    if (!apiUrl) return;

    dispatch(setLoading(true));
    dispatch(setChartOpen(false));
    dispatch(setLoopMeasurementCurveChartData([]));

    const MIN_LOADING_TIME_MS = 1000;
    const startTime = Date.now();

    try {
      const response = await fetch(apiUrl, {
        method: "GET",
        headers: { "Content-Type": "application/json" },
      });

      if (!response.ok) throw new Error(`Fehler: ${response.status}`);

      const jsonData = await response.json();
      const elapsedTime = Date.now() - startTime;
      const waitTime = Math.max(0, MIN_LOADING_TIME_MS - elapsedTime);
      await new Promise((resolve) => setTimeout(resolve, waitTime));
      //------------------------
      console.log("▶️ Lade Daten für:");
      console.log("  Slot:", slotNumber);
      console.log("  Typ:", selectedSlotType, "→", type);
      console.log("  Modus:", selectedMode);
      console.log("  Von:", vonDatum);
      console.log("  Bis:", bisDatum);
      console.log("  URL:", apiUrl);
      console.log("  Daten:", jsonData);

      //-----------------------

      if (Array.isArray(jsonData) && jsonData.length > 0) {
        dispatch(setLoopMeasurementCurveChartData(jsonData));
        dispatch(setChartOpen(true));
      } else {
        alert("⚠️ Keine Messdaten im gewählten Zeitraum gefunden.");
        dispatch(setLoopMeasurementCurveChartData([]));
        dispatch(setChartOpen(false));
      }
    } catch (err) {
      console.error("❌ Fehler beim Laden der Daten:", err);
      alert("❌ Fehler beim Laden der Daten.");
    } finally {
      dispatch(setLoading(false));
    }
  };

  return (
    <div className="flex justify-between items-center p-2 bg-gray-100 rounded-lg space-x-2">
      <div className="flex items-center">
        <label className="text-sm font-semibold">
          Steckplatz {slotNumber ?? "-"}
        </label>
      </div>

      <div className="flex items-center space-x-2">
        <DateRangePicker />

        <select
          value={selectedMode}
          onChange={(e) => {
            dispatch(
              setSelectedMode(e.target.value as "DIA0" | "DIA1" | "DIA2")
            );
            dispatch(setBrushRange({ startIndex: 0, endIndex: 0 }));
          }}
          className="px-3 py-1 bg-white border rounded text-sm"
        >
          <option value="DIA0">Alle Messwerte</option>
          <option value="DIA1">Stündliche Werte</option>
          <option value="DIA2">Tägliche Werte</option>
        </select>

        <select
          value={selectedSlotType}
          onChange={(e) => {
            const value = e.target.value as
              | "isolationswiderstand"
              | "schleifenwiderstand";
            dispatch(setSelectedSlotType(value));
            dispatch(
              setChartTitle(
                value === "isolationswiderstand"
                  ? "Isolationsmessung"
                  : "Schleifenmessung"
              )
            );
          }}
          className="px-3 py-1 bg-white border rounded text-sm"
        >
          <option value="isolationswiderstand">Isolationswiderstand</option>
          <option value="schleifenwiderstand">Schleifenwiderstand</option>
        </select>

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

        {isLoading && (
          <div className="flex items-center space-x-2 text-sm text-gray-500">
            <div className="w-4 h-4 border-2 border-t-2 border-blue-500 rounded-full animate-spin" />
            <span>Lade Daten...</span>
          </div>
        )}
      </div>
    </div>
  );
};

export default LoopChartActionBar;
