import React, { createContext, useEffect, useState } from 'react'
import { UniversalWalletConnector } from '@meshconnect/uwc-core'
import type {
  Session,
  Network,
  WalletMetadata,
  WalletConnectConfig,
  TonConnectConfig
} from '@meshconnect/uwc-types'

// Guard against double initialization
let sharedConnector: UniversalWalletConnector | null = null

interface ConnectionContextValue {
  connector: UniversalWalletConnector
  session: Session
  wallets: WalletMetadata[]
  networks: Network[]
  isReady: boolean
}

const ConnectionContext = createContext<ConnectionContextValue | null>(null)

interface ConnectionProviderProps {
  children: React.ReactNode
  networks: Network[]
  wallets: WalletMetadata[]
  usingIntegratedBrowser?: boolean
  walletConnectConfig?: WalletConnectConfig
  tonConnectConfig?: TonConnectConfig
}

export function ConnectionProvider({
  children,
  networks,
  wallets,
  usingIntegratedBrowser = false,
  walletConnectConfig,
  tonConnectConfig
}: ConnectionProviderProps) {
  if (!sharedConnector) {
    sharedConnector = new UniversalWalletConnector(
      networks,
      wallets,
      usingIntegratedBrowser,
      walletConnectConfig,
      tonConnectConfig
    )
  }

  const connector = sharedConnector

  const [session, setSession] = useState<Session>(() => connector.getSession())
  const [isReady, setIsReady] = useState(() => connector.isReady())

  useEffect(() => {
    const unsubscribe = connector.subscribe(() => {
      setSession(connector.getSession())
      setIsReady(connector.isReady())
    })

    return unsubscribe
  }, [connector])

  const value: ConnectionContextValue = {
    connector,
    session,
    wallets: connector.getWallets(),
    networks: connector.getNetworks(),
    isReady
  }

  return (
    <ConnectionContext.Provider value={value}>
      {children}
    </ConnectionContext.Provider>
  )
}

export { ConnectionContext }
