"use client";
// pages/_app.tsx
import { useEffect, useState } from "react";
import { loadWindowVariables } from "../utils/loadWindowVariables";
import Header from "../components/header/Header";
import Navigation from "../components/navigation/Navigation";
import Footer from "../components/footer/Footer";
import "../styles/globals.css";
import { Provider } from "react-redux";
import { setVariables } from "../redux/slices/variablesSlice";
import { setSystemSettings } from "../redux/slices/systemSettingsSlice"; // ✅ System-Settings
import {
  setOpcUaZustand,
  setOpcUaActiveClientCount,
  setOpcUaNodesetName,
} from "../redux/slices/opcuaSettingsSlice"; // ✅ OPC-UA Settings
import store from "../redux/store";
import { AppProps } from "next/app";
import WindowVariablesInitializer from "../components/WindowVariablesInitializer";

function MyApp({ Component, pageProps }: AppProps) {
  const [sessionExpired, setSessionExpired] = useState(false);

  useEffect(() => {
    const loadAndStoreVariables = async () => {
      try {
        const variables = await loadWindowVariables();
        if (!variables) throw new Error("Sitzungsfehler");

        // ✅ OPC-UA Werte, System-Settings und last20Messages separat speichern
        const {
          last20Messages, // Entfernen für eigenes Redux-Slice
          opcUaZustand,
          opcUaActiveClientCount,
          opcUaNodesetName,
          deviceName,
          mac1,
          ip,
          subnet,
          gateway,
          cplInternalTimestamp,
          ntp1,
          ntp2,
          ntp3,
          ntpTimezone,
          ntpActive,
          de,
          de_label,
          de_state,
          da_state,
          da_bezeichnung,
          ...restVariables
        } = variables;

        // ✅ Speichere System-Settings in systemSettingsSlice
        store.dispatch(
          setSystemSettings({
            deviceName,
            mac1,
            ip,
            subnet,
            gateway,
            cplInternalTimestamp,
            ntp1,
            ntp2,
            ntp3,
            ntpTimezone,
            ntpActive,
          })
        );

        // ✅ Speichere OPC-UA Einstellungen in opcuaSettingsSlice
        store.dispatch(setOpcUaZustand(opcUaZustand || "Offline"));
        store.dispatch(setOpcUaActiveClientCount(opcUaActiveClientCount || 0));
        store.dispatch(
          setOpcUaNodesetName(opcUaNodesetName || "DefaultNodeset")
        );

        // ✅ Speichere alle anderen Variablen in variablesSlice
        store.dispatch(setVariables(restVariables));

        setSessionExpired(false);
      } catch (error) {
        console.error("Fehler beim Laden der Sitzung:", error);
        setSessionExpired(true);
      }
    };

    if (typeof window !== "undefined") {
      loadAndStoreVariables(); // Initiales Laden

      // Intervall zum Aktualisieren des Redux-Stores alle 10 Sekunden
      const intervalId = setInterval(loadAndStoreVariables, 10000);

      // Bereinigen des Intervalls, wenn die Komponente unmountet wird
      return () => clearInterval(intervalId);
    }
  }, []);

  return (
    <Provider store={store}>
      <WindowVariablesInitializer />
      <div className="flex flex-col h-screen overflow-hidden">
        <Header />
        <div className="flex flex-grow w-full">
          <Navigation className="w-1/5" />
          <main className="w-full flex-grow">
            {sessionExpired && (
              <div className="bg-red-500 text-white p-4 text-center">
                Ihre Sitzung ist abgelaufen oder die Verbindung ist
                unterbrochen. Bitte laden Sie die Seite neu.
              </div>
            )}
            <Component {...pageProps} />
          </main>
        </div>
        <Footer />
      </div>
    </Provider>
  );
}

export default MyApp;
