import { useState, useCallback, useEffect } from 'react';
import Config from 'react-native-config';

import '@walletconnect/react-native-compat';
import '@ethersproject/shims';
import { Core } from '@walletconnect/core';
import { ICore } from '@walletconnect/types';
import { Web3Wallet, IWeb3Wallet } from '@walletconnect/web3wallet';

export let web3wallet: IWeb3Wallet;
export let core: ICore;

export async function createWeb3Wallet() {
  const core = new Core({
    projectId: Config.WALLET_CONNECT_PROJECT_ID,
  });

  web3wallet = await Web3Wallet.init({
    core,
    metadata: {
      name: 'Laconic Wallet',
      description: 'Laconic Wallet',
      url: 'https://wallet.laconic.com/',
      icons: ['https://avatars.githubusercontent.com/u/92608123'],
    },
  });
}

export default function useInitialization() {
  const [initialized, setInitialized] = useState(false);

  const onInitialize = useCallback(async () => {
    try {
      await createWeb3Wallet();
      setInitialized(true);
    } catch (err: unknown) {
      console.log('Error for initializing', err);
    }
  }, []);

  useEffect(() => {
    if (!initialized) {
      onInitialize();
    }
  }, [initialized, onInitialize]);

  return initialized;
}

export async function web3WalletPair(params: { uri: string }) {
  return await web3wallet.core.pairing.pair({ uri: params.uri });
}
