"use client"; // app/kabelueberwachung/page.jsx
import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Kue705FO from "../../components/modules/Kue705FO";

function Kabelueberwachung() {
  const router = useRouter();
  const [activeRack, setActiveRack] = useState(1); // Track the active rack
  const [kueIso, setKueIso] = useState([]); // State to store isolation values
  const [kueID, setKueID] = useState([]); // State to store the KUE names
  const [schleifenwiderstand, setSchleifenwiderstand] = useState([]); // State to store the resistance values
  const [kueOnline, setKueOnline] = useState([]); // State to store the module status

  // Verwende den useRouter Hook, um den Rack-Parameter zu extrahieren
  useEffect(() => {
    const query = new URLSearchParams(window.location.search);
    const rackParam = query.get("rack");

    if (rackParam) {
      setActiveRack(parseInt(rackParam)); // Setze das aktive Rack basierend auf dem URL-Parameter
    }
  }, [router.query]);

  // Load the external JavaScript file and fetch the isolation values
  useEffect(() => {
    if (window.kueIso && Array.isArray(window.kueIso)) {
      setKueIso(window.kueIso); // Store the isolation values from the global variable
    }

    if (window.kueRes && Array.isArray(window.kueRes)) {
      setSchleifenwiderstand(window.kueRes); // Store the resistance values from the global variable
    }

    if (window.kueOnline && Array.isArray(window.kueOnline)) {
      setKueOnline(window.kueOnline); // Store the module status from the global variable
    }
    if (window.kueID && Array.isArray(window.kueID)) {
      setKueID(window.kueID); // Store the KUE names from the global variable
    }
  }, []);

  // Zuerst alle Werte der Arrays speichern
  const allModules = kueIso.map((iso, index) => ({
    isolationswert: iso,
    schleifenwiderstand: schleifenwiderstand[index],
    modulName: kueID[index] || "Unknown",
    kueOnlineStatus: kueOnline[index],
  }));

  // Dann die Module für jedes Rack in 8er-Gruppen aufteilen
  const racks = {
    rack1: allModules.slice(0, 8),
    rack2: allModules.slice(8, 16),
    rack3: allModules.slice(16, 24),
    rack4: allModules.slice(24, 32),
  };
  // Log the racks in the console for debugging
  /*   console.log("Rack 1:", racks.rack1);
  console.log("Rack 2:", racks.rack2);
  console.log("Rack 3:", racks.rack3);
  console.log("Rack 4:", racks.rack4); */

  // Function to handle rack change
  const changeRack = (rack) => {
    setActiveRack(rack);
  };

  useEffect(() => {
    const script = document.createElement("script");
    // Dynamischer Pfad basierend auf der Umgebung
    const environment = process.env.NEXT_PUBLIC_NODE_ENV || "production";
    if (environment === "production") {
      script.src = `CPL?/SERVICE/kueData.js`; // Produktions-Pfad
    } else {
      script.src = `/mockData/kueData.js`; // Mock-Daten-Pfad
    }
    script.async = true;
    document.body.appendChild(script);

    // Cleanup the script if the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []);

  return (
    <div className="bg-gray-100 flex-1 p-6">
      <h1 className="text-2xl mb-4">Kabelüberwachung</h1>

      <div className="mb-4">
        <button
          onClick={() => changeRack(1)}
          className={`mr-1 ${
            activeRack === 1
              ? "bg-littwin-blue text-white p-1 rounded-sm "
              : "bg-gray-300 p-1 text-sm"
          }`}
        >
          Rack 1
        </button>
        <button
          onClick={() => changeRack(2)}
          className={`mr-2 ${
            activeRack === 2
              ? "bg-littwin-blue text-white p-1 rounded-sm"
              : "bg-gray-300 p-1 text-sm"
          }`}
        >
          Rack 2
        </button>
        <button
          onClick={() => changeRack(3)}
          className={`mr-2 ${
            activeRack === 3
              ? "bg-littwin-blue text-white p-1 rounded-sm"
              : "bg-gray-300 p-1 text-sm"
          }`}
        >
          Rack 3
        </button>
        <button
          onClick={() => changeRack(4)}
          className={`mr-2 ${
            activeRack === 4
              ? "bg-littwin-blue text-white p-1 rounded-sm"
              : "bg-gray-300 p-1 text-sm"
          }`}
        >
          Rack 4
        </button>
      </div>

      <div className="flex flex-row space-x-4 scale-110 ml-[5%] mt-[5%]">
        {racks[`rack${activeRack}`].map((slot, index) => {
          const slotIndex = index + (activeRack - 1) * 8;
          const alarmStatus =
            (window.kueAlarm1 && window.kueAlarm1[slotIndex]) ||
            (window.kueAlarm2 && window.kueAlarm2[slotIndex]) ||
            (window.kueCableBreak && window.kueCableBreak[slotIndex]) ||
            (window.kueGroundFault && window.kueGroundFault[slotIndex]);

          return (
            <div key={index} className="flex">
              <Kue705FO
                isolationswert={slot.isolationswert}
                schleifenwiderstand={slot.schleifenwiderstand}
                modulName={slot.modulName}
                kueOnline={slot.kueOnlineStatus}
                alarmStatus={alarmStatus} // Pass the calculated alarm status
                slotIndex={slotIndex}
              />
              {/*   
              console.log(`Module Data (Rack ${activeRack}, Slot ${index + 1}):`,slot);
              */}
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default Kabelueberwachung;
