"use client";
import React, { useState, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Kue705FO from "../components/modules/kue705FO/Kue705FO";
import { useDispatch, useSelector } from "react-redux";

function Kabelueberwachung() {
  const router = useRouter();
  const dispatch = useDispatch();
  const searchParams = useSearchParams(); // URL-Parameter holen
  const initialRack = parseInt(searchParams.get("rack")) || 1; // Rack-Nummer aus URL oder 1

  const [activeRack, setActiveRack] = useState(initialRack); // Nutze initialRack als Startwert
  const [alarmStatus, setAlarmStatus] = useState([]); // Alarmstatus

  // Redux-Variablen aus dem Store abrufen
  const {
    kueOnline,
    kueID,
    kueIso,
    kueAlarm1,
    kueAlarm2,
    kueResidence,
    kueCableBreak,
    kueGroundFault,
  } = useSelector((state) => state.variables);

  // Alarmstatus basierend auf Redux-Variablen berechnen
  const updateAlarmStatus = () => {
    const updatedAlarmStatus = kueIso.map((_, index) => {
      return (
        (kueAlarm1 && kueAlarm1[index]) ||
        (kueAlarm2 && kueAlarm2[index]) ||
        (kueCableBreak && kueCableBreak[index]) ||
        (kueGroundFault && kueGroundFault[index])
      );
    });
    setAlarmStatus(updatedAlarmStatus);
  };

  // Alarmstatus initial berechnen und alle 10 Sekunden aktualisieren
  useEffect(() => {
    updateAlarmStatus();
    const interval = setInterval(updateAlarmStatus, 10000);
    return () => clearInterval(interval);
  }, [kueIso, kueAlarm1, kueAlarm2, kueCableBreak, kueGroundFault]);

  // Modul- und Rack-Daten aufbereiten
  const allModules = kueIso.map((iso, index) => ({
    isolationswert: iso,
    schleifenwiderstand: kueResidence[index],
    modulName: kueID[index] || `Modul ${index + 1}`, // Eindeutiger Name pro Index
    kueOnlineStatus: kueOnline[index],
    alarmStatus: alarmStatus[index],
  }));
  //console.log("Alle Module:", allModules);

  const racks = {
    rack1: allModules.slice(0, 8),
    rack2: allModules.slice(8, 16),
    rack3: allModules.slice(16, 24),
    rack4: allModules.slice(24, 32),
  };

  // Konsolenausgaben für jede Rack-Aufteilung
  /*   console.log(
    "Rack 1 Module:",
    racks.rack1.map((slot) => slot.modulName)
  );
  console.log(
    "Rack 2 Module:",
    racks.rack2.map((slot) => slot.modulName)
  );
  console.log(
    "Rack 3 Module:",
    racks.rack3.map((slot) => slot.modulName)
  );
  console.log(
    "Rack 4 Module:",
    racks.rack4.map((slot) => slot.modulName)
  ); */

  // Funktion zum Wechseln des Racks
  const changeRack = (rack) => {
    setActiveRack(rack);
    console.log(`Aktives Rack geändert zu: ${rack}`);
  };

  useEffect(() => {
    /*     console.log(`Aktives Rack: ${activeRack}`);
    console.log(
      `Rack ${activeRack} Modulnamen:`,
      racks[`rack${activeRack}`].map((slot) => slot.modulName)
    ); */
  }, [activeRack, racks]);

  return (
    <div className="bg-gray-100 flex-1 p-6 text-black xl:p-4 2xl:p-6  h-[calc(100vh-13vh-8vh)]">
      <h1 className="text-2xl xl:text-xl mb-4">Kabelüberwachung</h1>
      <div className="mb-4">
        {[1, 2, 3, 4].map((rack) => (
          <button
            key={rack}
            onClick={() => changeRack(rack)}
            className={`mr-2 ${
              Number(activeRack) === Number(rack)
                ? "bg-littwin-blue text-white p-1 rounded-sm"
                : "bg-gray-300 p-1 text-sm"
            }`}
          >
            Rack {rack}
          </button>
        ))}
      </div>
      <div className="flex flex-row space-x-8 xl:space-x-0 2xl:space-x-8  ml-[5%] mt-[5%]">
        {racks[`rack${activeRack}`].map((slot, index) => {
          const slotIndex = index + (activeRack - 1) * 8;
          return (
            <div key={index} className="flex">
              <Kue705FO
                isolationswert={slot.isolationswert}
                schleifenwiderstand={slot.schleifenwiderstand}
                modulName={slot.modulName}
                kueOnline={slot.kueOnlineStatus}
                alarmStatus={slot.alarmStatus}
                slotIndex={slotIndex}
              />
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default Kabelueberwachung;
