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

import { getSignParamsMessage } from '../utils/wallet-connect/Helpers';
import { web3wallet } from '../utils/wallet-connect/WalletConnectUtils';
import {
  approveEIP155Request,
  rejectEIP155Request,
} from '../utils/wallet-connect/EIP155Requests';

import styles from '../styles/stylesheet';
import { SignModalProps } from '../types';

const SignModal = ({
  visible,
  setModalVisible,
  requestEvent,
  requestSession,
}: SignModalProps) => {
  if (!requestEvent || !requestSession) {
    return null;
  }

  const chainID = requestEvent?.params?.chainId?.toUpperCase();
  const message = getSignParamsMessage(requestEvent?.params?.request?.params);

  const requestName = requestSession?.peer?.metadata?.name;
  const requestIcon = requestSession?.peer?.metadata?.icons[0];
  const requestURL = requestSession?.peer?.metadata?.url;

  const { topic } = requestEvent;

  const onApprove = async () => {
    if (requestEvent) {
      const response = await approveEIP155Request(requestEvent);
      await web3wallet.respondSessionRequest({
        topic,
        response,
      });
      setModalVisible(false);
    }
  };

  const onReject = async () => {
    if (requestEvent) {
      const response = rejectEIP155Request(requestEvent);
      await web3wallet.respondSessionRequest({
        topic,
        response,
      });
      setModalVisible(false);
    }
  };

  return (
    <Modal visible={visible} animationType="slide" transparent>
      <View style={styles.container}>
        <View style={styles.modalContentContainer}>
          <Text variant="titleLarge">Sign this message?</Text>

          <Image
            style={styles.dappLogo}
            source={{
              uri: requestIcon,
            }}
          />

          <Text>{requestName}</Text>
          <Text variant="bodyMedium">{requestURL}</Text>

          <View style={styles.messageBody}>
            <Text variant="bodyLarge">{message}</Text>
          </View>
          <Text>Chains: {chainID}</Text>

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

export default SignModal;
