import React, { createContext, useContext, useEffect, useState } from 'react';

import { SessionTypes } from '@walletconnect/types';

import { WalletConnectContextProps } from '../types';
import useInitialization, {
  web3wallet,
} from '../utils/wallet-connect/WalletConnectUtils';

const WalletConnectContext = createContext<WalletConnectContextProps>({
  requestSession: {},
  setRequestSession: () => {},
  activeSessions: {},
  setActiveSessions: () => {},
});

const useWalletConnect = () => {
  const walletConnectContext = useContext(WalletConnectContext);
  return walletConnectContext;
};

const WalletConnectProvider = ({ children }: { children: React.ReactNode }) => {
  useInitialization();

  useEffect(() => {
    const sessions = web3wallet?.getActiveSessions() ?? {};
    setActiveSessions(sessions);
  }, []);

  const [requestSession, setRequestSession] = useState<any>({});
  const [activeSessions, setActiveSessions] = useState<
    Record<string, SessionTypes.Struct>
  >({});

  return (
    <WalletConnectContext.Provider
      value={{
        requestSession,
        setRequestSession,
        activeSessions,
        setActiveSessions,
      }}>
      {children}
    </WalletConnectContext.Provider>
  );
};

export { useWalletConnect, WalletConnectProvider };
