"use client"; // /pages/kabelueberwachung.tsx
import React, { useState, useEffect } from "react";
import { useSearchParams } from "next/navigation";
import Kue705FO from "@/components/main/kabelueberwachung/kue705FO/Kue705FO";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch } from "@/redux/store"; // Adjust the path to your Redux store file
import { RootState } from "@/redux/store"; // Adjust the path to your Redux store file
import { getKueDataThunk } from "@/redux/thunks/getKueDataThunk";

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

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

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

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

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

  // Modul- und Rack-Daten aufbereiten
  const allModules = kueIso.map((iso: number | string, index: number) => ({
    isolationswert: iso,
    schleifenwiderstand: kueResidence[index],
    modulName: kueID[index] || `Modul ${index + 1}`, // Eindeutiger Name pro Index
    kueOnlineStatus: kueOnline[index],
    alarmStatus: alarmStatus[index],
    tdrLocation: [], // Placeholder, replace with actual tdrLocation if available
    win_fallSensorsActive: kueOnline[index] ? 1 : 0, // Beispielwert, anpassen je nach Logik
  }));
  //console.log("Alle Module:", allModules);

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

  // 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: number) => {
    setActiveRack(rack);
    console.log(`Aktives Rack geändert zu: ${rack}`);
  };

  useEffect(() => {
    /*     console.log(`Aktives Rack: ${activeRack}`);
    console.log(
      `Rack ${activeRack} Modulnamen:`,
      racks[`rack${activeRack as 1 | 2 | 3 | 4}` as keyof typeof racks].map((slot: any) => slot.modulName)
    ); */
  }, [activeRack, racks]);

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

  //------------------------------------------------------------
  useEffect(() => {
    if (kueIso.length === 0) {
      console.log("📦 Lade KUE-Daten aus getKueDataThunk...");
      dispatch(getKueDataThunk());
    }
  }, [dispatch, kueIso.length]);
  //------------------------------------------------------------

  // JSX rendering
  return (
    <div>
      <div className="mb-4">
        {[1, 2, 3, 4].map((rack) => {
          const isActive = Number(activeRack) === Number(rack);
          return (
            <button
              key={rack}
              onClick={() => changeRack(rack)}
              aria-pressed={isActive}
              className={`mr-2 px-2 py-1 rounded-sm text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-accent/50 ${
                isActive
                  ? "btn-primary"
                  : "btn-muted text-fg-muted hover:text-fg"
              }`}
            >
              Rack {rack}
            </button>
          );
        })}
      </div>
      <div className="flex flex-row space-x-8 xl:space-x-0 2xl:space-x-8 qhd:space-x-16 ml-[5%] mt-[5%]">
        {(
          racks[
            `rack${activeRack as 1 | 2 | 3 | 4}` as keyof typeof racks
          ] as typeof allModules
        ).map(
          (
            slot: {
              isolationswert: number | string;
              schleifenwiderstand: number | string;
              modulName: string;
              kueOnlineStatus: number;
              alarmStatus?: boolean;
              tdrLocation: number[];
              win_fallSensorsActive: number;
            },
            index: number
          ) => {
            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}
                  tdrLocation={slot.tdrLocation}
                  win_fallSensorsActive={slot.win_fallSensorsActive}
                />
              </div>
            );
          }
        )}
      </div>
    </div>
  );
}

export default KabelueberwachungView;
