"use client"; // components/main/uebersicht/Baugruppentraeger.tsx
import React, { useMemo, useEffect } from "react";
import { useSelector } from "react-redux";
import { useRouter } from "next/navigation";
import { RootState, useAppDispatch } from "../../../redux/store";
import KabelModulStatus from "./modulesStatus/KabelModulStatus";
import { fetchKueDataThunk } from "../../../redux/thunks/fetchKueDataThunk";

const Baugruppentraeger: React.FC = () => {
  const dispatch = useAppDispatch();
  const router = useRouter(); // useRouter für Navigation hinzufügen

  // Redux-Variablen direkt hier abrufen
  const {
    kueOnline: kueOnlineRaw,
    kueVersion,
    kueCableBreak,
    kueAlarm1,
    kueAlarm2,
    kueGroundFault,
  } = useSelector((state: RootState) => state.kueDataSlice);

  // `kueOnline` sicherstellen, dass es nur Zahlen enthält
  const kueOnline = useMemo(
    () =>
      kueOnlineRaw.map((value) =>
        typeof value === "string" ? parseFloat(value) || 0 : value
      ),
    [kueOnlineRaw]
  );

  // Klick-Handler für Routing
  const handleModuleClick = (rackNumber: number) => {
    router.push(`/kabelueberwachung?rack=${rackNumber}`);
  };

  const baugruppen: JSX.Element[] = [];
  const numBaugruppen = Math.ceil(kueOnline.length / 8);

  for (let i = 0; i < numBaugruppen; i++) {
    const slots = kueOnline.slice(i * 8, (i + 1) * 8);

    baugruppen.push(
      <div
        key={i}
        className="flex bg-white shadow-md rounded-lg mb-4 xl:mb-0 lg:mb-0 border border-gray-200 w-full laptop:scale-y-75 xl:scale-y-90"
      >
        <div className="flex gap-1">
          {slots.map((version, index) => {
            const slotNumber = i * 8 + index + 1;
            const isSlotOnline = kueOnline[slotNumber - 1] === 1;
            const rawModuleVersion = kueVersion[slotNumber - 1] || version;

            // Sicherstellen, dass moduleVersion eine Zahl ist
            const moduleVersion =
              typeof rawModuleVersion === "number"
                ? rawModuleVersion
                : parseFloat(rawModuleVersion) || 0;

            const rackNumber = Math.ceil(slotNumber / 8);

            return (
              <div
                key={slotNumber}
                className="cursor-pointer"
                onClick={() => handleModuleClick(rackNumber)}
              >
                <KabelModulStatus
                  slot={slotNumber}
                  isOnline={isSlotOnline}
                  moduleVersion={moduleVersion}
                  kueCableBreak={kueCableBreak}
                  kueAlarm1={kueAlarm1}
                  kueAlarm2={kueAlarm2}
                  kueGroundFault={kueGroundFault}
                />
              </div>
            );
          })}
        </div>
      </div>
    );
  }
  //--------------------------------------------
  useEffect(() => {
    dispatch(fetchKueDataThunk());
  }, [dispatch]);
  //--------------------------------------------
  return <>{baugruppen}</>;
};

export default Baugruppentraeger;
