"use client"; // components/modules/Kue705FO.jsx
import React, { useState, useEffect, useRef } from "react";
import ReactModal from "react-modal";
import Chart from "chart.js/auto";
import { useSelector } from "react-redux";
import KueModal from "../modales/KueModal";
import "bootstrap-icons/font/bootstrap-icons.css"; // Import Bootstrap Icons

function Kue705FO({
  isolationswert,
  schleifenwiderstand,
  modulName,
  kueOnline,
  slotIndex,
  tdrLocation,
  alarmStatus,
}) {
  console.log(
    `Rendering Kue705FO - SlotIndex: ${slotIndex}, ModulName: ${modulName}`
  );

  const chartRef = useRef(null);
  const [zoomPlugin, setZoomPlugin] = useState(null); // Plugin-Status für Chart.js
  const [kueVersion, setKueVersion] = useState("V4.19");
  const [currentAlarmStatus, setCurrentAlarmStatus] = useState(false);
  const [currentModulName, setCurrentModulName] = useState(modulName);
  const [activeButton, setActiveButton] = useState("Schleife");
  const [loopTitleText, setloopTitleText] = useState(
    "Schleifenwiderstand [kOhm]"
  );
  const [loopDisplayValue, setLoopDisplayValue] = useState(schleifenwiderstand); // Initialisiere den loopDisplayValue mit schleifenwiderstand

  const [isoDisplayText, setIsoDisplayText] = useState("Aderbruch");
  const [groundFaultDisplayText, setGroundFaultDisplayText] =
    useState("Erdschluss");
  const [loopFaultDisplayText, setLoopFaultDisplayText] =
    useState("Schleifenfehler");
  const [isoFaultDisplayText, setIsoFaultDisplayText] =
    useState("Isolationsfehler");
  const [isoGreaterThan200, setIsoGreaterThan200] = useState(">200 MOhm");

  const [loading, setLoading] = useState(false);
  const [isoDisplayValue, setIsoDisplayValue] = useState(isolationswert);
  const [showModal, setShowModal] = useState(false);
  const [showChartModal, setShowChartModal] = useState(false);
  const [chartData, setChartData] = useState(null);

  // Redux-Variablen abrufen
  const {
    kuePSTmMinus96V,
    kueCableBreak,
    kueGroundFault,
    kueAlarm1,
    kueAlarm2,
    kueOverflow,
    kueVersion: reduxKueVersion,
    tdrActive,
  } = useSelector((state) => state.variables);

  const handleOpenModal = () => setShowModal(true);
  const handleCloseModal = () => setShowModal(false);

  const handleOpenChartModal = () => {
    setShowChartModal(true);
    if (activeButton === "TDR") {
      loadTDRChartData();
    } else {
      loadLoopChartData();
    }
  };
  const handleButtonClick = (button) => {
    if (button === "Schleife") {
      setActiveButton("Schleife");
      setloopTitleText("Schleifenwiderstand [kOhm]");
      setLoopDisplayValue(schleifenwiderstand); // Setze den Wert auf schleifenwiderstand
    } else if (button === "TDR") {
      setActiveButton("TDR");
      setloopTitleText("Entfernung [Km]");
      setLoopDisplayValue(
        tdrLocation && tdrLocation[slotIndex] !== undefined
          ? tdrLocation[slotIndex]
          : "0"
      ); // Setze den Wert auf tdrLocation oder "0" als Fallback
    }
  };

  // Funktion für die Schleifenmessung
  const goLoop = () => {
    let slot = slotIndex;

    if (slot >= 32) {
      return;
    }

    let slotFormat = slot < 10 ? `0${slot}` : `${slot}`;

    setLoading(true); // Setze den Ladezustand auf true
    alert(`Schleifenmessung wird für Slot ${slot + 1} gestartet...`);

    fetch(`/CPL?kabelueberwachung.html&KS_${slotFormat}=1&slot=${slot}`, {
      method: "GET",
    })
      .then((response) => {
        if (response.ok) {
          alert(`Schleifenmessung erfolgreich gestartet für Slot ${slot + 1}`);
          console.log("Schleifenmessung erfolgreich gestartet für Slot", slot);
        } else {
          alert("Fehler beim Starten der Schleifenmessung.");
          console.error("Fehler beim Senden der Schleifen-Anfrage");
        }
      })
      .catch((error) => {
        alert("Ein Fehler ist aufgetreten.");
        console.error("Fehler:", error);
      })
      .finally(() => setLoading(false)); // Ladezustand zurücksetzen
  };
  // Funktion für die TDR-Messung
  const goTDR = () => {
    //-------------------------------------------------
    let slot = slotIndex;

    if (slot >= 32) {
      return;
    }

    let slotFormat = slot < 10 ? `0${slot}` : `${slot}`;

    setLoading(true);
    alert(`TDR wird für Slot ${slot + 1} gestartet...`);
    fetch(
      `/CPL?Service/Kabelueberwachung.html&KTT${slotFormat}=1&slot=${slot}`,
      {
        method: "GET",
      }
    )
      .then((response) => {
        if (response.ok) {
          alert(`TDR erfolgreich gestartet für Slot ${slot + 1}`);
          console.log("TDR erfolgreich gestartet für Slot", slot + 1);
        } else {
          console.error("Fehler beim Senden der TDR-Anfrage");
        }
      })
      .catch((error) => {
        console.error("Fehler:", error);
      })
      .finally(() => setLoading(false));
  };
  // Bestimme, welche Funktion ausgeführt wird, basierend auf dem aktiven Button
  const handleRefreshClick = () => {
    if (activeButton === "Schleife") {
      goLoop(); // Wenn Schleife aktiv ist, starte goLoop
    } else if (activeButton === "TDR") {
      goTDR(); // Wenn TDR aktiv ist, starte goTDR
    }
  };

  const handleCloseChartModal = () => setShowChartModal(false);
  // Funktion zum Erstellen des TDR-Charts

  const createTDRChart = (dataTDR) => {
    const ctx = document.getElementById("myChart").getContext("2d");

    new Chart(ctx, {
      type: "line",
      data: {
        labels: dataTDR.map((row) => row.t),
        datasets: [
          {
            label: "Pegel",
            data: dataTDR.map((row) => row.m),
            borderColor: "#00AEEF",
            borderWidth: 1,
            pointBorderWidth: 0,
            pointStyle: false,
            fill: false,
            yAxisID: "y",
          },
        ],
      },
      options: {
        scales: {
          x: {
            type: "linear",
            position: "left",
            title: { display: true, text: "Meter" },
          },
        },
        plugins: {
          zoom: {
            pan: {
              enabled: true,
              mode: "xy",
            },
            zoom: {
              wheel: {
                enabled: true, // Zoom mit Mausrad
              },
              pinch: {
                enabled: true, // Pinch-Zoom für Touchgeräte
              },
              mode: "xy", // x und y Achsen zoomen
            },
          },
        },
      },
    });
  };

  const loadTDRChartData = () => {
    const slot = slotIndex;
    const environment = process.env.NODE_ENV || "production";
    const fileData =
      environment === "production"
        ? `/CPL?/CPL/lastTDR/slot${slot}.json`
        : `/CPLmockData/lastTDR/slot${slot}.json`;

    fetch(fileData)
      .then((response) => response.json())
      .then((data) => {
        setChartData(data);
        createTDRChart(data);
      })
      .catch((error) =>
        console.error("Fehler beim Laden der TDR-Messkurvendaten:", error)
      );
  };

  const loadLoopChartData = () => {
    const slot = slotIndex;
    const environment = process.env.NODE_ENV || "production";
    const fileData =
      environment === "production"
        ? `/CPL?/CPL/4000values/slot${slot}.json`
        : `/CPLmockData/4000values/slot${slot}.json`;

    fetch(fileData)
      .then((response) => response.json())
      .then((data) => {
        setChartData(data);
        createLoopChart(data, "Schleifenmesskurve");
      })
      .catch((error) =>
        console.error("Fehler beim Laden der Schleifenmesskurvendaten:", error)
      );
  };

  // Füge das Plugin zu Chart.js hinzu
  useEffect(() => {
    // Lade das Plugin nur, wenn `window` verfügbar ist
    if (typeof window !== "undefined") {
      import("chartjs-plugin-zoom").then((mod) => {
        setZoomPlugin(mod.default); // Setze das Plugin
        Chart.register(mod.default); // Plugin zur Chart.js-Instanz registrieren
      });
    }
  }, []);

  const createLoopChart = (data) => {
    const ctx = document.getElementById("myChart").getContext("2d");
    new Chart(ctx, {
      type: "line",
      data: {
        labels: data
          .map((row) => new Date(row.t).toLocaleString("de-DE"))
          .reverse(),
        datasets: [
          {
            label: "Isolationswiderstand (MOhm)",
            data: data.map((row) => row.m).reverse(),
            borderColor: "#00AEEF",
            borderWidth: 1,
            lineTension: 0.1,
            pointRadius: 0.3,
            pointHoverRadius: 5,
            fill: false,
            yAxisID: "y",
          },
          {
            label: "Schleifenwiderstand (kOhm)",
            data: data.map((row) => row.n).reverse(),
            borderColor: "black",
            borderWidth: 1,
            lineTension: 0.1,
            pointRadius: 0.3,
            pointHoverRadius: 5,
            fill: false,
            yAxisID: "y1",
          },
        ],
      },
      options: {
        scales: {
          y: {
            type: "linear",
            position: "left",
            title: { display: true, text: "MOhm" },
          },
          y1: {
            type: "linear",
            position: "right",
            title: { display: true, text: "kOhm" },
          },
        },
        plugins: {
          zoom: {
            pan: {
              enabled: true,
              mode: "xy",
            },
            zoom: {
              wheel: {
                enabled: true, // Zoom mit Mausrad
              },
              pinch: {
                enabled: true, // Pinch-Zoom für Touchgeräte
              },
              mode: "xy", // x und y Achsen zoomen
            },
          },
        },
      },
    });
  };

  useEffect(() => {
    const updateAlarmStatus = () => {
      const alarmStatus =
        (kueAlarm1 && kueAlarm1[slotIndex]) ||
        (kueAlarm2 && kueAlarm2[slotIndex]) ||
        (kueCableBreak && kueCableBreak[slotIndex]) ||
        (kueGroundFault && kueGroundFault[slotIndex]);

      setCurrentAlarmStatus(alarmStatus);
    };

    updateAlarmStatus();
    const interval = setInterval(updateAlarmStatus, 10000);
    return () => clearInterval(interval);
  }, [slotIndex, kueAlarm1, kueAlarm2, kueCableBreak, kueGroundFault]);

  useEffect(() => {
    if (reduxKueVersion?.[slotIndex]) {
      setKueVersion("V" + reduxKueVersion[slotIndex] / 100);
    }
  }, [slotIndex, reduxKueVersion]);
  //---------------------------------------------------
  // Funktion zum Aktualisieren der Anzeige basierend auf dem Alarmstatus mit Icon und Blinken
  useEffect(() => {
    let intervalId;

    // Funktion zum Blinken des Textes oder Icons
    const setBlinkingText = (text) => {
      intervalId = setInterval(() => {
        setIsoDisplayValue((prevValue) =>
          prevValue === text ? (
            <i
              className="bi bi-exclamation-triangle"
              style={{ fontSize: "24px", color: "red" }}
            ></i>
          ) : (
            text
          )
        );
      }, 5000); // Beispiel-Zyklus für 7 Sekunden
    };

    // Priorisierte Alarmanzeige
    if (kuePSTmMinus96V?.[slotIndex] === 1) {
      clearInterval(intervalId); // Stoppt das vorherige Intervall, falls aktiv
      setBlinkingText("PST-M prüfen");
    } else if (kueCableBreak?.[slotIndex] === 1) {
      clearInterval(intervalId);
      setBlinkingText(isoDisplayText);
    } else if (kueGroundFault?.[slotIndex] === 1) {
      clearInterval(intervalId);
      setBlinkingText(groundFaultDisplayText);
    } else if (kueAlarm1?.[slotIndex] === 1) {
      clearInterval(intervalId);
      setBlinkingText(isoFaultDisplayText);
    } else if (kueAlarm2?.[slotIndex] === 1) {
      clearInterval(intervalId);
      setBlinkingText(loopFaultDisplayText);
    } else if (kueOverflow?.[slotIndex] === 1) {
      clearInterval(intervalId);
      setIsoDisplayValue(isoGreaterThan200);
    } else {
      clearInterval(intervalId);
      setIsoDisplayValue(isolationswert); // Standardanzeige
    }

    // Cleanup bei Änderungen des Status oder Schließen des Effekts
    return () => clearInterval(intervalId);
  }, [
    slotIndex,
    isolationswert,
    isoDisplayText,
    groundFaultDisplayText,
    isoFaultDisplayText,
    loopFaultDisplayText,
    isoGreaterThan200,
    kuePSTmMinus96V,
    kueCableBreak,
    kueGroundFault,
    kueAlarm1,
    kueAlarm2,
    kueOverflow,
  ]);
  // In Kue705FO.jsx
  useEffect(() => {
    console.log("modulName for Kue705FO:", modulName);
  }, [modulName]);
  //---------------------------------------------------
  // Effekt, um Modulnamen zu aktualisieren, wenn sich der Prop ändert
  useEffect(() => {
    setCurrentModulName(modulName);
    console.log(`Modulname aktualisiert für Slot ${slotIndex}:`, modulName);
  }, [modulName, slotIndex]);
  //---------------------------------------------------
  // Aktualisiert den Schleifenwiderstand, wenn sich der `schleifenwiderstand`-Prop ändert
  useEffect(() => {
    if (activeButton === "Schleife") {
      setLoopDisplayValue(schleifenwiderstand);
    }
  }, [schleifenwiderstand, activeButton]);
  //---------------------------------------------------
  return (
    <div className="relative bg-gray-300 w-[116px] h-[390px] border border-gray-400 scale-110 top-3">
      {kueOnline === 1 ? (
        <>
          <div className="relative w-[113.202px] h-[242.492px] bg-littwin-blue border-[1.5px] border-gray-400 z-0">
            <div className="flex items-start justify-between h-[30px]">
              <div className="relative w-[20px] h-[20px] bg-gray-800 flex items-center justify-center">
                <span className="text-white text-[10px]">{slotIndex + 1}</span>
              </div>

              <h3 className="text-white font-bold text-[9px] mr-4">KÜ705-FO</h3>

              <button
                onClick={handleOpenModal}
                className="w-[15px] h-[15px] bg-gray-400 flex items-center justify-center"
              >
                <span className="text-white text-[20px]">⚙</span>
              </button>
            </div>
            {}
            <KueModal
              showModal={showModal}
              onClose={handleCloseModal}
              slot={slotIndex}
              onModulNameChange={setCurrentModulName}
            />
            <div className="flex flex-col mt-[10px] ml-[10px]">
              <div className="flex items-center space-x-4 mt-[10px]">
                <div className="flex flex-col items-start space-y-1 mr-1">
                  <span className="text-white text-[10px]">Betrieb</span>
                  <span className="text-white text-[10px]">Alarm</span>
                </div>
                <div className="flex flex-col items-center space-y-3">
                  <div className="w-[10px] h-[10px] bg-green-500 rounded-full"></div>
                  <div
                    className={`w-[10px] h-[10px] rounded-full ${
                      currentAlarmStatus ? "bg-red-500" : "bg-gray-300"
                    }`}
                  ></div>
                </div>
              </div>
            </div>

            {/* Anzeige des Isolation */}
            <div className="relative mt-[50px] mx-auto bg-black text-white w-[100px] h-[40px] flex items-center justify-center text-[18px] z-10">
              <div className="text-center">
                <span
                  className={
                    kuePSTmMinus96V?.[slotIndex] === 1 ||
                    kueCableBreak?.[slotIndex] === 1 ||
                    kueGroundFault?.[slotIndex] === 1 ||
                    kueAlarm1?.[slotIndex] === 1 ||
                    kueAlarm2?.[slotIndex] === 1
                      ? "text-red-500 text-[14px]"
                      : kueOverflow?.[slotIndex] === 1
                      ? "text-white text-[14px]"
                      : ""
                  }
                >
                  {isoDisplayValue}
                </span>

                {kuePSTmMinus96V?.[slotIndex] !== 1 &&
                  kueCableBreak?.[slotIndex] !== 1 &&
                  kueGroundFault?.[slotIndex] !== 1 &&
                  kueAlarm1?.[slotIndex] !== 1 &&
                  kueAlarm2?.[slotIndex] !== 1 &&
                  kueOverflow?.[slotIndex] !== 1 && (
                    <div className="text-[8px]">ISO MOhm</div>
                  )}
              </div>
            </div>

            <div className="absolute top-0 left-[75px] w-[3px] h-full bg-white z-0"></div>
            <div className="absolute top-[40px] left-[75px] w-[40px] h-[3px] bg-white z-0"></div>

            <div className="absolute bottom-[20px] left-0 right-0 text-black text-[10px] bg-gray-300 p-1 text-center">
              {currentModulName || `Modul ${slotIndex + 1}`}
            </div>

            <div className="absolute bottom-1 right-1 text-black text-[8px]">
              {kueVersion}
            </div>
          </div>

          {/* loopDisplay: Zeigt Schleifenwiderstand oder TDR-Distanz an, je nach Modus */}
          <div className="absolute bottom-1 left-[1.095px] w-[113.182px] h-[130px] bg-gray-300 border-[1.5px] border-gray-400 p-1">
            <span className="text-black text-[7px] absolute top-[2px] left-1 mt-1">
              {loopTitleText}
            </span>

            <div className="relative w-full h-[45px] bg-gray-100 border border-gray-400 flex items-center justify-center mt-3">
              <button
                onClick={handleRefreshClick} // Dynamische Funktion basierend auf aktivem Button
                className="absolute -top-1 -right-1 w-[20px] h-[20px] bg-gray-400 flex items-center justify-center"
                disabled={loading} // Disable button while loading
              >
                <span className="text-white text-[18px]">⟳</span>
              </button>

              <div className="absolute bottom-[5px] left-1/2 transform -translate-x-1/2 w-[100px] flex justify-center items-center">
                <div className="text-center text-black text-[10px]">
                  <p>
                    {loopDisplayValue +
                      (activeButton === "Schleife" ? " KOhm" : " Km")}
                  </p>
                </div>
              </div>
            </div>

            <div className="flex mt-2 space-x-1">
              <button
                onClick={() => handleButtonClick("Schleife")}
                className={`w-[50%] h-[25px] text-white text-[10px] flex items-center justify-center ${
                  activeButton === "Schleife"
                    ? "bg-littwin-blue"
                    : "bg-gray-400"
                }`}
              >
                Schleife
              </button>
              <button
                onClick={() => handleButtonClick("TDR")}
                className={`w-[50%] h-[25px] text-white text-[10px] flex items-center justify-center ${
                  tdrActive[slotIndex] === 0
                    ? "bg-gray-200 cursor-not-allowed" // Deaktiviert: Hellgrau
                    : activeButton === "TDR"
                    ? "bg-littwin-blue" // Aktiviert: Littwin Blau
                    : "bg-gray-400" // Nicht geklickt: Dunkelgrau
                }`}
                disabled={tdrActive[slotIndex] === 0} // Button deaktiviert, wenn TDR für diesen Slot nicht aktiv ist
              >
                TDR
              </button>
            </div>

            <button
              onClick={handleOpenChartModal} // Öffnet das Chart-Modal
              className="w-full h-[25px] bg-littwin-blue text-white text-[10px] flex items-center justify-center mt-1"
            >
              Messkurve
            </button>
          </div>

          {/* Modal für Messkurve */}
          {showChartModal && (
            <ReactModal
              isOpen={showChartModal}
              onRequestClose={handleCloseChartModal}
              ariaHideApp={false}
              style={{
                overlay: { backgroundColor: "rgba(0, 0, 0, 0.5)" },
                content: {
                  top: "50%",
                  left: "50%",
                  right: "auto",
                  bottom: "auto",
                  marginRight: "-50%",
                  transform: "translate(-50%, -50%)",
                  width: "95%",
                  maxWidth: "1200px",
                  height: "650px",
                  padding: "10px",
                },
              }}
            >
              <button
                onClick={handleCloseChartModal}
                style={{
                  position: "absolute",
                  top: "10px",
                  right: "10px",
                  background: "transparent",
                  border: "none",
                  fontSize: "24px",
                  cursor: "pointer",
                }}
              >
                <i className="bi bi-x-circle-fill"></i>{" "}
                {/* Bootstrap Icon "X" */}
              </button>
              <h2>Messkurve Slot {slotIndex + 1}</h2>
              <canvas
                id="myChart"
                ref={chartRef}
                style={{ width: "100%", height: "600px" }}
              ></canvas>
            </ReactModal>
          )}
        </>
      ) : (
        <div className="flex items-center justify-center h-full text-gray-500">
          <p>Kein Modul im Slot {slotIndex + 1}</p>
        </div>
      )}
    </div>
  );
}

export default Kue705FO;
