import React, { PropsWithChildren, useMemo, useState } from 'react'

import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react'

import { ChainType, ProviderConfigs, getSolanaWalletAdapters } from '../../core'
import {
  SolanaConnectionPromise,
  SolanaConnectorContext
} from '../../store/solana-connector/context'
import { useChains } from '../../store/wallet'

interface SolanaConnectorProviderProps {
  providerConfigs: ProviderConfigs
}

export const SolanaConnectorProvider: React.FC<PropsWithChildren<SolanaConnectorProviderProps>> = ({
  providerConfigs,
  children
}) => {
  const { chains, chainId } = useChains()
  const chain = useMemo(() => chains.find((item) => item.chainId === chainId), [chainId, chains])
  const [connectionPromise, setConnectionPromise] = useState<SolanaConnectionPromise | undefined>(
    undefined
  )
  const [visible, setVisible] = useState<boolean>(false)
  const wallets = useMemo(() => getSolanaWalletAdapters(providerConfigs), [providerConfigs])

  return (
    <SolanaConnectorContext.Provider
      value={{ visible, setVisible, connectionPromise, setConnectionPromise }}
    >
      <ConnectionProvider
        endpoint={
          chain && chain.type === ChainType.Solana
            ? chain.rpcUrls[0]
            : 'https://api.mainnet-beta.solana.com'
        }
      >
        <WalletProvider wallets={wallets}>{children}</WalletProvider>
      </ConnectionProvider>
    </SolanaConnectorContext.Provider>
  )
}
