import { useCallback } from 'react';

import { WalletName } from '@solana/wallet-adapter-base';
import { useWallet } from '@solana/wallet-adapter-react';

import { DemonWalletName } from '../adapters/index';
import {
  getDemonWalletUrl, handleRedirectIfDemonNotInstalled,
  isDemonWalletDetected,
  isRunningInCypress,
} from '../helpers';
import { useWalletModal } from './useWalletModal';

export const useConnectWallet = () => {
  const { wallet, connect, select } = useWallet()
  const { visible, setVisible } = useWalletModal()

  const connectWallet = useCallback(() => {
    if (isRunningInCypress) {
      select('E2E' as WalletName<'E2E'>)
      connect().catch((e) => {
        console.log('e', e)
      })
    } else {
      if (wallet) {
        if (wallet?.adapter?.url) {
          wallet.adapter.url = getDemonWalletUrl();
        }
        if (wallet.adapter.name === DemonWalletName) {
          if (!isDemonWalletDetected()) {
            setVisible(!visible)
            return
          }
        }
        connect().catch((e) => {
          console.log('e', e)
        })
      } else {
        setVisible(!visible)
      }
    }
  }, [
    connect,
    select,
    setVisible,
    visible,
    wallet,
  ])

  return {
    connectWallet,
  }
}
