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 let currentETHAddresses: string[];
export let currentCosmosAddresses: string[];

import { useState, useCallback, useEffect } from 'react';
import { retrieveAccounts } from '../accounts';

export async function createWeb3Wallet() {
  const { ethLoadedAccounts } = await retrieveAccounts();
  currentETHAddresses = ethLoadedAccounts
    ? ethLoadedAccounts.map(ethAccount => ethAccount.address)
    : [];

  // TODO: Move to dotenv
  const ENV_PROJECT_ID = 'c97365bf9f06d12a7488de36240b0ff4';
  const core = new Core({
    projectId: ENV_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 });
}
