"use client";
// pages/_app.tsx

import { useEffect, useState } from "react";
import { Provider } from "react-redux";
import store, { useAppDispatch } from "../redux/store";
import { loadWindowVariables } from "../utils/loadWindowVariables";
import Header from "../components/header/Header";
import Navigation from "../components/navigation/Navigation";
import Footer from "../components/footer/Footer";
import WindowVariablesInitializer from "../components/WindowVariablesInitializer";
import "../styles/globals.css";
import { AppProps } from "next/app";
import { setVariables } from "../redux/slices/variablesSlice";
import { setSystemSettings } from "../redux/slices/systemSettingsSlice";
import {
  setOpcUaZustand,
  setOpcUaActiveClientCount,
  setOpcUaNodesetName,
} from "../redux/slices/opcuaSettingsSlice";
import { fetchAnalogeEingaengeThunk } from "../redux/thunks/fetchAnalogeEingaengeThunk";
import { fetchDigitaleEingaengeThunk } from "../redux/thunks/fetchDigitaleEingaengeThunk";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Provider store={store}>
      <AppContent Component={Component} pageProps={pageProps} />
    </Provider>
  );
}

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

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

        console.log("✅ Window-Variablen geladen:", variables);

        const {
          last20Messages,
          opcUaZustand,
          opcUaActiveClientCount,
          opcUaNodesetName,
          deviceName,
          mac1,
          ip,
          subnet,
          gateway,
          cplInternalTimestamp,
          ntp1,
          ntp2,
          ntp3,
          ntpTimezone,
          ntpActive,
          ...restVariables
        } = variables;

        dispatch(
          setSystemSettings({
            deviceName,
            mac1,
            ip,
            subnet,
            gateway,
            cplInternalTimestamp,
            ntp1,
            ntp2,
            ntp3,
            ntpTimezone,
            ntpActive,
          })
        );

        dispatch(setOpcUaZustand(opcUaZustand || "Offline"));
        dispatch(setOpcUaActiveClientCount(opcUaActiveClientCount || 0));
        dispatch(setOpcUaNodesetName(opcUaNodesetName || "DefaultNodeset"));

        dispatch(setVariables(restVariables));

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

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

      const intervalId = setInterval(loadAndStoreVariables, 10000);
      return () => clearInterval(intervalId);
    }
  }, []);
  //---------------------------------------------------------
  useEffect(() => {
    if (typeof window !== "undefined") {
      dispatch(fetchAnalogeEingaengeThunk());
      const interval = setInterval(() => {
        dispatch(fetchAnalogeEingaengeThunk());
      }, 10000);
      return () => clearInterval(interval);
    }
  }, [dispatch]);
  //---------------------------------------------------------
  useEffect(() => {
    if (typeof window !== "undefined") {
      dispatch(fetchDigitaleEingaengeThunk());
      const interval = setInterval(() => {
        dispatch(fetchDigitaleEingaengeThunk());
      }, 10000);
      return () => clearInterval(interval);
    }
  }, [dispatch]);
  //---------------------------------------------------------
  return (
    <div className="flex flex-col h-screen overflow-hidden">
      <WindowVariablesInitializer />
      <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>
  );
}

export default MyApp;
