"use client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactNode, Suspense, useEffect, useState } from "react";
import { Toaster } from "react-hot-toast";
import { wsService } from "../lib/websocket";
import ErrorBoundary from "./components/ErrorBoundary";
import Loading from "./components/Loading";
import { NotificationProvider } from "./components/NotificationContext";

export default function Providers({ children }: { children: ReactNode }) {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            retry: (failureCount, error) => {
              // Don't retry on 4xx errors
              if (
                error instanceof Error &&
                "status" in error &&
                typeof error.status === "number"
              ) {
                if (error.status >= 400 && error.status < 500) {
                  return false;
                }
              }
              // Retry up to 3 times for other errors
              return failureCount < 3;
            },
            staleTime: 5 * 60 * 1000, // 5 minutes
            gcTime: 10 * 60 * 1000 // 10 minutes
          },
          mutations: {
            retry: 1
          }
        }
      })
  );

  useEffect(() => {
    // Connect to WebSocket server
    wsService.connect();

    // Cleanup on unmount
    return () => {
      wsService.disconnect();
    };
  }, []);

  return (
    <ErrorBoundary>
      <QueryClientProvider client={queryClient}>
        <NotificationProvider>
          <Suspense
            fallback={<Loading message="Loading application..." size="lg" />}
          >
            {children}
          </Suspense>
          <Toaster
            position="top-right"
            toastOptions={{
              duration: 4000,
              style: {
                background: "var(--toast-bg, #363636)",
                color: "var(--toast-color, #fff)",
                top: "80px" // Position below the 64px header + some padding
              }
            }}
          />
        </NotificationProvider>
      </QueryClientProvider>
    </ErrorBoundary>
  );
}
