'use client'

import { ApolloProvider } from '@apollo/client'
import { getApolloClient } from '@/lib/graphql/client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useState, useMemo } from 'react'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import { Toaster } from '@/components/ui/toaster'

export function Providers({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            staleTime: 60 * 1000, // 1 minute
            refetchOnWindowFocus: false,
            retry: (failureCount, error) => {
              // Don't retry on 4xx errors
              if (error && typeof error === 'object' && 'statusCode' in error) {
                const statusCode = error.statusCode as number
                if (statusCode >= 400 && statusCode < 500) {
                  return false
                }
              }
              return failureCount < 3
            },
          },
          mutations: {
            retry: false,
          },
        },
      })
  )

  // Create Apollo Client only on client side
  const apolloClient = useMemo(() => getApolloClient(), [])

  return (
    <ApolloProvider client={apolloClient}>
      <QueryClientProvider client={queryClient}>
        {children}
        {process.env.NODE_ENV === 'development' && <ReactQueryDevtools initialIsOpen={false} />}
        <Toaster />
      </QueryClientProvider>
    </ApolloProvider>
  )
}

