"use client";

import {
  QueryClient,
  QueryClientProvider,
  useQueryClient,
} from "@tanstack/react-query";
import { type ReactNode, useEffect, useState } from "react";
import { ViewPaddingsProvider } from "@/components/Componentes/view-paddings-provider";

function AppFocusReloader({ children }: { children: ReactNode }) {
  const queryClient = useQueryClient();

  useEffect(() => {
    if (typeof window !== "undefined") {
      (window as any).__queryClient = queryClient;
    }

    const handleReload = () => {
      // Invalidate all active queries so fresh data is reloaded from backend
      queryClient.invalidateQueries();
    };

    const handleVisibilityChange = () => {
      if (document.visibilityState === "visible") {
        handleReload();
      }
    };

    const handlePageShow = () => {
      handleReload();
    };

    window.addEventListener("focus", handleReload);
    window.addEventListener("pageshow", handlePageShow);
    document.addEventListener("visibilitychange", handleVisibilityChange);

    // Listen for Flutter response events if available
    const win = window as any;
    const unbindFlutter =
      typeof win.addFlutterResponseListener === "function"
        ? win.addFlutterResponseListener(() => handleReload())
        : null;

    return () => {
      window.removeEventListener("focus", handleReload);
      window.removeEventListener("pageshow", handlePageShow);
      document.removeEventListener("visibilitychange", handleVisibilityChange);
      if (typeof unbindFlutter === "function") {
        unbindFlutter();
      }
    };
  }, [queryClient]);

  return <>{children}</>;
}

type ProvidersProps = {
  children: ReactNode;
};

export default function Providers({ children }: ProvidersProps) {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            refetchOnWindowFocus: "always",
            refetchOnMount: "always",
            refetchOnReconnect: "always",
            retry: 1,
            staleTime: 0, // Always consider queries stale to ensure fresh data from backend on every page load
            gcTime: 10 * 60 * 1000, // 10 minutes
          },
        },
      }),
  );

  return (
    <QueryClientProvider client={queryClient}>
      <AppFocusReloader>
        <ViewPaddingsProvider />
        {children}
      </AppFocusReloader>
    </QueryClientProvider>
  );
}
