import React, { useEffect } from 'react';
import { Image, TouchableOpacity, View } from 'react-native';
import { List, Text } from 'react-native-paper';

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

import { useWalletConnect } from '../context/WalletConnectContext';
import { web3wallet } from '../utils/wallet-connect/WalletConnectUtils';
import styles from '../styles/stylesheet';

export default function WalletConnect() {
  const { activeSessions, setActiveSessions } = useWalletConnect();

  const disconnect = async (sessionId: string) => {
    await web3wallet.disconnectSession({
      topic: sessionId,
      reason: getSdkError('USER_DISCONNECTED'),
    });
    const sessions = web3wallet.getActiveSessions();
    setActiveSessions(sessions);
    return;
  };

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

  return (
    <View>
      {Object.keys(activeSessions).length > 0 ? (
        <>
          <View style={{ marginLeft: 12, marginTop: 12 }}>
            <Text variant="titleMedium">Active Sessions</Text>
          </View>
          <List.Section>
            {Object.entries(activeSessions).map(
              ([sessionId, session], index) => (
                <List.Item
                  style={{ paddingLeft: 12, borderBottomWidth: 0.5 }}
                  key={sessionId}
                  title={`${session.peer.metadata.name}`}
                  descriptionNumberOfLines={7}
                  //TODO: Refactor
                  description={`${sessionId} \n\n${session.peer.metadata.url}\n\n${session.peer.metadata.description}`}
                  left={() => (
                    <Image
                      style={styles.dappLogo}
                      source={{ uri: session.peer.metadata.icons[0] }}
                    />
                  )}
                  right={() => (
                    <TouchableOpacity
                      onPress={() => disconnect(sessionId)}
                      style={{ display: 'flex', justifyContent: 'center' }}>
                      <List.Icon icon="close" />
                    </TouchableOpacity>
                  )}
                />
              ),
            )}
          </List.Section>
        </>
      ) : (
        <View style={{ display: 'flex', alignItems: 'center', marginTop: 12 }}>
          <Text>You have no active sessions</Text>
        </View>
      )}
    </View>
  );
}
