import React, { useCallback, useEffect, useMemo, useState } from 'react';

import { SignClientTypes } from '@walletconnect/types';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

import SignMessage from './components/SignMessage';
import HomeScreen from './components/HomeScreen';
import SignRequest from './components/SignRequest';
import InvalidPath from './components/InvalidPath';
import PairingModal from './components/PairingModal';
import WalletConnect from './components/WalletConnect';
import { StackParamsList } from './types';
import useInitialization, {
  web3wallet,
} from './utils/wallet-connect/WalletConnectUtils';
import { EIP155_SIGNING_METHODS } from './utils/wallet-connect/EIP155Lib';
import { useAccounts } from './context/AccountsContext';
import { getSignParamsMessage } from './utils/wallet-connect/Helpers';
import { navigationRef, navigateTo } from './utils/RootNavigation';
import { useRequests } from './context/RequestContext';

const Stack = createNativeStackNavigator<StackParamsList>();

const App = (): React.JSX.Element => {
  useInitialization();

  const { accounts } = useAccounts();

  const { requestSession, setRequestSession } = useRequests();

  const [modalVisible, setModalVisible] = useState(false);
  //TODO: Remove any
  const [currentProposal, setCurrentProposal] = useState<
    SignClientTypes.EventArguments['session_proposal'] | undefined
  >();

  const currentEthAddresses = useMemo(() => {
    if (accounts.ethAccounts.length > 0) {
      return accounts.ethAccounts.map(account => account.address);
    }
    return [];
  }, [accounts]);

  const onSessionProposal = useCallback(
    (proposal: SignClientTypes.EventArguments['session_proposal']) => {
      setModalVisible(true);
      setCurrentProposal(proposal);
    },
    [],
  );

  const onSessionRequest = useCallback(
    async (requestEvent: SignClientTypes.EventArguments['session_request']) => {
      const { topic, params } = requestEvent;
      const { request } = params;
      const address = request.params[1];
      const message = getSignParamsMessage(request.params);
      const requestSessionData =
        web3wallet.engine.signClient.session.get(topic);

      switch (request.method) {
        case EIP155_SIGNING_METHODS.ETH_SIGN:
        case EIP155_SIGNING_METHODS.PERSONAL_SIGN:
          setRequestSession(requestSessionData);
          if (address && message) {
            navigateTo('SignRequest', {
              network: 'eth',
              address,
              message,
              requestEvent,
              requestSession,
            });
          }
          return;
      }
    },
    [requestSession, setRequestSession],
  );
  useEffect(() => {
    web3wallet?.on('session_proposal', onSessionProposal);
    web3wallet?.on('session_request', onSessionRequest);

    return () => {
      web3wallet?.off('session_proposal', onSessionProposal);
      web3wallet?.off('session_request', onSessionRequest);
    };
    //TODO: Investigate dependancies
  });

  const linking = {
    prefixes: ['https://www.laconic-wallet.com'],
    config: {
      screens: {
        SignRequest: {
          path: 'sign/:network/:address/:message',
        },
      },
    },
  };

  return (
    <NavigationContainer linking={linking} ref={navigationRef}>
      <Stack.Navigator>
        <Stack.Screen
          name="Laconic"
          component={HomeScreen}
          options={{
            title: 'Laconic Wallet',
            headerBackVisible: false,
          }}
        />
        <Stack.Screen
          name="SignMessage"
          component={SignMessage}
          options={{
            title: 'Sign Message',
          }}
          initialParams={{ selectedNetwork: 'Ethereum' }}
        />
        <Stack.Screen
          name="SignRequest"
          component={SignRequest}
          options={{
            title: 'Sign this message?',
          }}
        />
        <Stack.Screen
          name="InvalidPath"
          component={InvalidPath}
          options={{
            title: 'Bad Request',
            headerBackVisible: false,
          }}
        />
        <Stack.Screen
          name="WalletConnect"
          component={WalletConnect}
          options={{
            title: 'Connect Wallet',
          }}
        />
      </Stack.Navigator>
      <PairingModal
        visible={modalVisible}
        setModalVisible={setModalVisible}
        currentProposal={currentProposal}
        setCurrentProposal={setCurrentProposal}
        currentEthAddresses={currentEthAddresses}
      />
    </NavigationContainer>
  );
};

export default App;
