"use client"; // /pages/kabelueberwachung.tsx
import React, { useState, useEffect } from "react";
import { useRouter, 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 { fetchAllTDRChartData } from "../redux/thunks/fetchAllTDRChartThunk";
import { fetchAllTDRReferenceChartThunk } from "../redux/thunks/fetchAllTDRReferenceChartThunk";
import { fetchLoopChartDataThunk } from "../redux/thunks/fetchLoopChartDataThunk";
import { fetchAllTDMData } from "../redux/thunks/fetchAllTDMThunk";

function Kabelueberwachung() {
  const dispatch: AppDispatch = 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.kueData);

  //----------------------------------------------------------------
  // 🚀 **TDR-Daten bereits in Redux abrufen**
  // Redux-Variablen abrufen
  const tdrData = useSelector((state) => state.tdrChart.data);
  const loading = useSelector((state) => state.tdrChart.loading);
  const error = useSelector((state) => state.tdrChart.error);

  // Beim Laden der Seite TDR-Daten abrufen
  useEffect(() => {
    if (!tdrData || tdrData.length === 0) {
      // console.log("TDR-Daten abrufen...");
      dispatch(fetchAllTDRChartData());
      dispatch(fetchAllTDRReferenceChartThunk());
    }
  }, [dispatch, tdrData]);
  //----------------------------------------------------------------
  // 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]);

  //-----------------------------------------------------------
  const {
    data: loopData,
    loading: loopLoading,
    error: loopError,
  } = useSelector((state: RootState) => state.loopChart);

  // Daten für alle Kombinationen laden (z. B. Slot 1 als Beispiel)
  useEffect(() => {
    ["DIA0", "DIA1", "DIA2"].forEach((mode) => {
      [3, 4].forEach((type) => {
        dispatch(
          fetchLoopChartDataThunk({
            mode: mode as "DIA0" | "DIA1" | "DIA2",
            type,
            slotNumber: 1,
            vonDatum: "2025-03-20",
            bisDatum: "2025-03-23",
          })
        );
      });
    });
  }, [dispatch]);

  // Zugriff z. B. auf Schleifenwiderstand von DIA1
  const dia1Schleifen = loopData["DIA1"]?.[4];
  const dia0Iso = loopData["DIA0"]?.[3];

  //------------------------------------------------------------
  const tdmData = useSelector((state) => state.tdmChart.data);

  useEffect(() => {
    if (!tdmData || tdmData.length === 0) {
      dispatch(fetchAllTDMData());
    }
  }, [dispatch, tdmData]);

  //----------------------------------------------------------------
  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;
