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

import { useEffect, useState } from "react";
import { Provider } from "react-redux";

import { useAppDispatch } from "@/redux/store";
import { AppProps } from "next/app";

import Header from "@/components/header/Header";
import Navigation from "@/components/navigation/Navigation";
import Footer from "@/components/footer/Footer";
import { store } from "@/redux/store";
import Script from "next/script";
import DeviceEventsBridge from "@/components/common/DeviceEventsBridge";
import GlobalActivityOverlay from "@/components/common/GlobalActivityOverlay";
import { usePathname } from "next/navigation";

// Thunks importieren
import { getKueDataThunk } from "@/redux/thunks/getKueDataThunk";
import { getAnalogInputsThunk } from "@/redux/thunks/getAnalogInputsThunk";
import { getDigitalOutputsThunk } from "@/redux/thunks/getDigitalOutputsThunk";
import { getAnalogInputsHistoryThunk } from "@/redux/thunks/getAnalogInputsHistoryThunk";
import { getLast20MessagesThunk } from "@/redux/thunks/getLast20MessagesThunk";
import { getOpcUaSettingsThunk } from "@/redux/thunks/getOpcUaSettingsThunk";
import { getSystemSettingsThunk } from "@/redux/thunks/getSystemSettingsThunk";
import { getSystemVoltTempThunk } from "@/redux/thunks/getSystemVoltTempThunk";
import { getReferenceCurveBySlotThunk } from "@/redux/thunks/getReferenceCurveBySlotThunk";
import { getAllTDRReferenceChartThunk } from "@/redux/thunks/getAllTDRReferenceChartThunk";
import { getTDRChartDataByIdThunk } from "@/redux/thunks/getTDRChartDataByIdThunk";
import { getLoopChartDataThunk } from "@/redux/thunks/getLoopChartDataThunk";
import { getAuthThunks } from "@/redux/thunks/getAuthThunks";
import { loadKvzData } from "@/redux/thunks/kvzThunks";
import Modal from "react-modal";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

if (typeof window !== "undefined") {
  Modal.setAppElement("#__next"); // oder "#root", je nach App-Struktur
}

import "@/styles/globals.css";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Provider store={store}>
      {/* Load global data: dev -> API mock JS; prod -> real device JS from public */}
      {process.env.NODE_ENV === "development" ? (
        <Script
          src="/api/cpl/kabelueberwachungAPIHandler"
          strategy="afterInteractive"
        />
      ) : (
        <Script src="/CPL/SERVICE/kueData.js" strategy="afterInteractive" />
      )}
      <AppContent Component={Component} pageProps={pageProps} />
      {/* Bridge window events -> Redux (works across all pages) */}
      <DeviceEventsBridge />
    </Provider>
  );
}

function AppContent({
  Component,
  pageProps,
}: {
  Component: AppProps["Component"];
  pageProps: AppProps["pageProps"];
}): JSX.Element {
  const dispatch = useAppDispatch();
  const pathnameHook = usePathname();
  const [sessionExpired] = useState(false);
  const mode = "DIA0"; // oder aus Router oder Session
  const type = 0; // Beispiel: 0 für "loop", 1 für "iso" (bitte ggf. anpassen)
  const [pathname, setPathname] = useState(
    typeof window !== "undefined" ? window.location.pathname : ""
  );

  useEffect(() => {
    const handleRouteChange = () => {
      setPathname(window.location.pathname);
    };

    window.addEventListener("popstate", handleRouteChange);
    window.addEventListener("pushstate", handleRouteChange);

    return () => {
      window.removeEventListener("popstate", handleRouteChange);
      window.removeEventListener("pushstate", handleRouteChange);
    };
  }, []);

  useEffect(() => {
    let intervalId: NodeJS.Timeout;

    const loadAndDispatch = () => {
      dispatch(getAuthThunks());

      // KVZ-Daten beim Start laden
      dispatch(loadKvzData());

      if (pathname.includes("kabelueberwachung")) {
        dispatch(getKueDataThunk());
      } else if (pathname.includes("analogInputs")) {
        dispatch(getAnalogInputsThunk());
      } else if (pathname.includes("digitalOutputs")) {
        dispatch(getDigitalOutputsThunk());
      } else if (pathname.includes("analogHistory")) {
        dispatch(
          getAnalogInputsHistoryThunk({
            eingang: 1, // Beispielwert, ggf. dynamisch setzen
            zeitraum: "tag", // Beispielwert, ggf. dynamisch setzen
            vonDatum: new Date().toISOString().split("T")[0], // heutiges Datum
            bisDatum: new Date().toISOString().split("T")[0], // heutiges Datum
          })
        );
      } else if (pathname.includes("dashboard")) {
        dispatch(getLast20MessagesThunk());
      } else if (pathname.includes("einstellungen")) {
        dispatch(getOpcUaSettingsThunk());
      } else if (pathname.includes("systemvolt")) {
        dispatch(getSystemVoltTempThunk());
      } else if (pathname.includes("system")) {
        dispatch(getSystemSettingsThunk());
      } else if (pathname.includes("tdrRef")) {
        dispatch(getAllTDRReferenceChartThunk());
      } else if (pathname.includes("tdrSlot")) {
        dispatch(getReferenceCurveBySlotThunk(1));
      } else if (pathname.includes("tdrId")) {
        dispatch(getTDRChartDataByIdThunk(1));
      } else if (pathname.includes("loopChart")) {
        dispatch(
          getLoopChartDataThunk({
            mode,
            type,
            slotNumber: 1, // Beispielwert, ggf. anpassen
            vonDatum: new Date().toISOString().split("T")[0], // Beispiel: heutiges Datum
            bisDatum: new Date().toISOString().split("T")[0], // Beispiel: heutiges Datum
          })
        );
      }
    };

    if (typeof window !== "undefined") {
      loadAndDispatch();
      intervalId = setInterval(loadAndDispatch, 10000);
      return () => clearInterval(intervalId);
    }
  }, [pathname, dispatch]);

  return (
    <div className="flex flex-col h-screen overflow-hidden">
      <Header />
      <div className="flex flex-grow w-full">
        <Navigation className="w-56" />
        <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} />
          <ToastContainer position="top-right" autoClose={3000} />
          {/* Hide global overlay on kabelueberwachung page so only per-slot overlays show */}
          {pathnameHook?.includes("kabelueberwachung") ? null : (
            <GlobalActivityOverlay />
          )}
        </main>
      </div>
      <Footer />
    </div>
  );
}

export default MyApp;
