// src/components/providers.tsx
'use client'
import { ThemeProvider } from 'next-themes'
import { useEffect, useState } from 'react'
import '@workspace/ui/globals.css'
import { Toaster } from 'sonner'
import { OctokitProviderWithRouter } from '@/context/OctokitProviderWithRouter'
import { WalletContextProvider } from '@/context/WalletContextProvider' 
import { BackendProvider } from '@/context/BackendContext'
import { GQLClientProvider } from '@/context'
import { GQLClient } from '@workspace/gql-client'

export function Providers({ children }: { children: React.ReactNode }) {
  const [gqlClient, setGqlClient] = useState<GQLClient | null>(null)
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    // Initialize GQLClient
    const initGQLClient = async () => {
      try {
        const client = new GQLClient({
          gqlEndpoint: `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'}/graphql`,
        })
        setGqlClient(client)
      } catch (error) {
        console.error('Failed to initialize GQL client:', error)
      } finally {
        setIsLoading(false)
      }
    }

    initGQLClient()
  }, [])

  if (isLoading || !gqlClient) {
    return <div>Loading...</div>
  }
  
  return (
    <ThemeProvider
      attribute="class"
      defaultTheme="system"
      enableSystem
      disableTransitionOnChange
      enableColorScheme
    >
      <Toaster />
      <WalletContextProvider>
        <BackendProvider>
          <GQLClientProvider client={gqlClient}>
            <OctokitProviderWithRouter>
              {children}
            </OctokitProviderWithRouter>
          </GQLClientProvider>
        </BackendProvider>
      </WalletContextProvider>
    </ThemeProvider>
  )
}