import React, { useEffect, useState } from 'react';
import { AppState, View } from 'react-native';
import { Button, Text, TextInput } from 'react-native-paper';
import {
  Camera,
  useCameraDevice,
  useCameraPermission,
  useCodeScanner,
} from 'react-native-vision-camera';

import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';

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

const WalletConnect = () => {
  const navigation =
    useNavigation<NativeStackNavigationProp<StackParamsList>>();

  const { hasPermission, requestPermission } = useCameraPermission();
  const device = useCameraDevice('back');

  const [currentWCURI, setCurrentWCURI] = useState<string>('');
  const [isActive, setIsActive] = useState(AppState.currentState === 'active');
  const [isScanning, setScanning] = useState(true);

  const codeScanner = useCodeScanner({
    codeTypes: ['qr'],
    onCodeScanned: codes => {
      if (isScanning) {
        codes.forEach(code => {
          if (code.value) {
            setCurrentWCURI(code.value);
            setScanning(false);
          }
        });
      }
    },
  });

  const pair = async () => {
    const pairing = await web3WalletPair({ uri: currentWCURI });
    navigation.navigate('Laconic');
    return pairing;
  };

  useEffect(() => {
    const handleAppStateChange = (newState: string) => {
      setIsActive(newState === 'active');
    };

    AppState.addEventListener('change', handleAppStateChange);

    if (!hasPermission) {
      requestPermission();
    }
  }, [hasPermission, isActive, requestPermission]);

  return (
    <View style={styles.appContainer}>
      {!hasPermission || !device ? (
        <Text>
          {!hasPermission ? 'No Camera Permission!' : 'No Camera Selected!'}
        </Text>
      ) : (
        <>
          <View style={styles.cameraContainer}>
            {isActive ? (
              <Camera
                style={styles.camera}
                device={device}
                isActive={isActive}
                codeScanner={codeScanner}
                video={false}
              />
            ) : (
              <Text>No Camera Selected!</Text>
            )}
          </View>

          <View style={styles.inputContainer}>
            <TextInput
              mode="outlined"
              onChangeText={setCurrentWCURI}
              value={currentWCURI}
              placeholder="Enter WalletConnect URI"
            />

            <View style={styles.signButton}>
              <Button mode="contained" onPress={pair}>
                Pair Session
              </Button>
            </View>
          </View>
        </>
      )}
    </View>
  );
};
export default WalletConnect;
