"use client";
import React, { useEffect } from "react";
import { useRouter } from "next/navigation";
import "tailwindcss/tailwind.css";
import "@fontsource/roboto";
import "bootstrap-icons/font/bootstrap-icons.css";
import { Icon } from "@iconify/react";
import { useDispatch } from "react-redux";
import {
  setOpcUaZustand,
  setOpcUaActiveClientCount,
  setOpcUaNodesetName,
} from "../redux/slices/variablesSlice";
import Last20MessagesTable from "../components/main/uebersicht/Last20MessagesTable";
import NetworkInfo from "../components/main/uebersicht/NetworkInfo";
import VersionInfo from "../components/main/uebersicht/VersionInfo";
import Baugruppentraeger from "../components/main/uebersicht/Baugruppentraeger";

const Dashboard: React.FC = () => {
  const router = useRouter();
  const dispatch = useDispatch();

  // Setzt OPC-UA-Werte beim Laden der Seite
  useEffect(() => {
    if (typeof window !== "undefined") {
      dispatch(setOpcUaZustand(window.win_opcUaZustand || "Unbekannt"));
      dispatch(
        setOpcUaActiveClientCount(
          Number(window.win_opcUaActiveClientCount) || 0
        )
      );
      dispatch(setOpcUaNodesetName(window.win_opcUaNodesetName || "Unbekannt"));
    }
  }, [dispatch]);

  return (
    <div className="flex flex-col gap-3 p-4 h-[calc(100vh-13vh-8vh)] laptop:h-[calc(100vh-10vh-5vh)] xl:h-[calc(100vh-10vh-6vh)] laptop:gap-0">
      {/* Header */}
      <div className="flex justify-between items-center w-full lg:w-2/3">
        <div className="flex justify-between gap-1">
          <Icon
            icon="ri:calendar-schedule-line"
            className="text-littwin-blue text-4xl xl:text-2xl"
          />
          <h1 className="text-xl font-bold text-gray-700 xl:text-base">
            Letzten 20 Meldungen
          </h1>
        </div>
      </div>

      {/* Hauptbereich mit Meldungstabelle und Baugruppenträger */}
      <div className="flex flex-col lg:flex-row gap-0 overflow-hidden flex-grow">
        <Last20MessagesTable />

        <div className="shadow-md rounded-lg w-full sm:w-3/4 md:w-2/3 lg:w-1/2 xl:w-1/3 flex flex-col gap-2">
          <div className="bg-gray-50 p-4 rounded-lg shadow-sm border border-gray-200 w-full">
            <VersionInfo />
          </div>

          {/* Jetzt holt sich Baugruppentraeger die Werte selbst aus Redux */}
          <Baugruppentraeger />
        </div>
      </div>

      <NetworkInfo />
    </div>
  );
};

export default Dashboard;
