// /components/main/kabelueberwachung/kue705FO/Charts/TDRChart/TDRChartActionBar.tsx

import React, { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import { useAppDispatch } from "../../../../../../redux/store";
import { RootState } from "../../../../../../redux/store";
import { fetchTDMDataBySlotThunk } from "../../../../../../redux/thunks/fetchTDMListBySlotThunk";
import { fetchTDRChartDataByIdThunk } from "../../../../../../redux/thunks/fetchTDRChartDataByIdThunk";
import { fetchReferenceCurveBySlotThunk } from "../../../../../../redux/thunks/fetchReferenceCurveBySlotThunk"; // ⬅ import ergänzen

const TDRChartActionBar: React.FC = () => {
  const dispatch = useAppDispatch();

  // ✅ Redux: selectedSlot aus kueChartMode (0-basiert)
  const selectedSlot = useSelector(
    (state: RootState) => state.kueChartModeSlice.selectedSlot
  );

  const tdmChartData = useSelector(
    (state: RootState) => state.tdmSingleChartSlice.data
  );

  const idsForSlot =
    selectedSlot !== null ? tdmChartData[selectedSlot] ?? [] : [];

  const tdrDataById = useSelector(
    (state: RootState) => state.tdrDataByIdSlice.dataById
  );
  const [selectedId, setSelectedId] = useState<number | null>(null);
  const currentChartData = selectedId !== null ? tdrDataById[selectedId] : [];

  // 🔄 Dropdown-Auswahl: neue Messung laden
  const handleSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const id = parseInt(e.target.value);
    setSelectedId(id);
    dispatch(fetchTDRChartDataByIdThunk(id));
  };

  // 📌 Referenz setzen (nutzt Slotnummer + 1 für die API)
  const handleSetReference = async () => {
    if (
      selectedSlot === null ||
      selectedId === null ||
      !currentChartData?.length
    )
      return;

    try {
      const slotNumber = selectedSlot + 1; // Slot ist 0-basiert, API will 1-basiert
      const isDev = process.env.NEXT_PUBLIC_NODE_ENV === "development";

      if (isDev) {
        await fetch("/api/cpl/updateTdrReferenceCurveAPIHandler", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            slot: slotNumber,
            data: currentChartData,
          }),
        });
      } else {
        const url = `/CPL?KTR${slotNumber}=${selectedId}`;
        await fetch(url, { method: "GET" });
      }
      if (!isDev) {
        const url = `/CPL?KTR${slotNumber}=${selectedId}`;
        const response = await fetch(url, { method: "GET" });

        if (!response.ok) {
          throw new Error(
            `Fehler beim Setzen der Referenz: ${response.statusText}`
          );
        }
      }

      // Optional: lokale Speicherung und Redux-Update
      localStorage.setItem(
        `ref-curve-slot${selectedSlot}`,
        JSON.stringify(currentChartData)
      );

      dispatch(fetchReferenceCurveBySlotThunk(selectedSlot));

      alert("Referenzkurve wurde erfolgreich gesetzt!");
    } catch (error) {
      console.error("Fehler beim Setzen der Referenzkurve:", error);
      alert("Fehler beim Setzen der Referenzkurve.");
    }
  };

  // 📥 Beim Slot-Wechsel TDM-Liste + letzte ID laden
  useEffect(() => {
    if (selectedSlot !== null) {
      dispatch(fetchTDMDataBySlotThunk(selectedSlot)).then((action: any) => {
        const slotData = action.payload?.data;
        if (slotData?.length > 0) {
          const lastId = slotData[0].id;
          setSelectedId(lastId);
          dispatch(fetchTDRChartDataByIdThunk(lastId));
        }
      });
    }
  }, [selectedSlot, dispatch]);

  return (
    <div className="flex justify-between items-center p-2 bg-gray-100 rounded-lg space-x-4">
      {/* 🧩 Slot-Anzeige (1-basiert für Benutzer) */}
      <div className="text-sm font-semibold">
        {selectedSlot !== null
          ? `Steckplatz ${selectedSlot + 1}`
          : "Kein Steckplatz gewählt"}
      </div>

      {/* ✅ Referenz setzen */}
      {selectedId !== null && (
        <button
          onClick={handleSetReference}
          className="border border-littwin-blue text-littwin-blue bg-white rounded px-3 py-1 text-sm hover:bg-blue-100"
        >
          TDR-Kurve als Referenz speichern
        </button>
      )}

      {/* 🔽 Dropdown für Messungen */}
      <div className="flex items-center space-x-2">
        <label htmlFor="tdrIdSelect" className="text-sm font-semibold">
          TDR Messung
        </label>
        <select
          id="tdrIdSelect"
          value={selectedId ?? ""}
          onChange={handleSelectChange}
          className="border rounded px-2 py-1 text-sm"
          disabled={idsForSlot.length === 0}
        >
          <option value="">-- Wähle Messung --</option>
          {idsForSlot.map((entry) => (
            <option key={entry.id} value={entry.id}>
              {new Date(entry.t).toLocaleString("de-DE", {
                day: "2-digit",
                month: "2-digit",
                year: "numeric",
                hour: "2-digit",
                minute: "2-digit",
                second: "2-digit",
              })}{" "}
              – Fehlerstelle: {entry.d} m
            </option>
          ))}
        </select>
      </div>
    </div>
  );
};

export default TDRChartActionBar;
