import React from 'react';
import { Image, View, Modal } from 'react-native';
import { Button, Text } from 'react-native-paper';

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

import { PairingModalProps } from '../types';
import styles from '../styles/stylesheet';
import { web3wallet } from '../utils/wallet-connect/WalletConnectUtils';

const PairingModal = ({
  visible,
  currentProposal,
  currentEthAddresses,
  setCurrentProposal,
  setModalVisible,
}: PairingModalProps) => {
  const url = currentProposal?.params?.proposer?.metadata.url;
  const methods = currentProposal?.params?.requiredNamespaces.eip155.methods;
  const events = currentProposal?.params?.requiredNamespaces.eip155.events;
  const chains = currentProposal?.params?.requiredNamespaces.eip155.chains;
  const icon = currentProposal?.params.proposer.metadata.icons[0];

  const handleAccept = async () => {
    if (currentProposal) {
      const { id, params } = currentProposal;
      const { requiredNamespaces, relays } = params;
      const namespaces: SessionTypes.Namespaces = {};
      Object.keys(requiredNamespaces).forEach(key => {
        const accounts: string[] = [];
        requiredNamespaces[key].chains!.map((chain: any) => {
          currentEthAddresses.map(acc => accounts.push(`${chain}:${acc}`));
        });

        namespaces[key] = {
          accounts,
          methods: requiredNamespaces[key].methods,
          events: requiredNamespaces[key].events,
        };
      });

      await web3wallet.approveSession({
        id,
        relayProtocol: relays[0].protocol,
        namespaces,
      });

      setModalVisible(false);
      setCurrentProposal(undefined);
    }
  };

  const handleReject = async () => {
    if (currentProposal) {
      const { id } = currentProposal;
      await web3wallet.rejectSession({
        id,
        reason: getSdkError('USER_REJECTED_METHODS'),
      });

      setModalVisible(false);
      setCurrentProposal(undefined);
    }
  };

  return (
    <Modal visible={visible} animationType="slide" transparent>
      <View style={styles.container}>
        <View style={styles.modalContentContainer}>
          {icon && (
            <Image
              style={styles.dappLogo}
              source={icon ? { uri: icon } : undefined}
            />
          )}

          <Text variant="bodyMedium">{url}</Text>
          <View style={styles.marginVertical8} />
          <Text variant="titleMedium">Connect to this site?</Text>
          <Text>Chains: {chains}</Text>

          <View style={styles.marginVertical8}>
            <Text variant="titleMedium">Methods Requested:</Text>
            {methods?.map(method => (
              <Text style={styles.centerText} key={method}>
                {method}
              </Text>
            ))}
          </View>

          <View style={styles.marginVertical8}>
            <Text variant="titleMedium">Events Requested:</Text>
            {events?.map(event => (
              <Text style={styles.centerText} key={event}>
                {event}
              </Text>
            ))}
          </View>

          <View style={styles.flexRow}>
            <Button mode="outlined" onPress={() => handleReject()}>
              Cancel
            </Button>
            <View style={styles.space} />
            <Button mode="contained" onPress={() => handleAccept()}>
              Accept
            </Button>
          </View>
        </View>
      </View>
    </Modal>
  );
};

export default PairingModal;
