import React, { useState } from 'react';
import { ScrollView, View, Alert } from 'react-native';
import { Button, Text, TextInput } from 'react-native-paper';

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

import { StackParamsList } from '../types';
import { addAccountFromHDPath } from '../utils';

type HDPathProps = NativeStackScreenProps<StackParamsList, 'HDPath'>;

const HDPath: React.FC<HDPathProps> = ({}) => {
  const [path, setPath] = useState<string>('');
  const [account, setAccount] = useState<any>(null);
  const [isAccountCreating, setIsAccountCreating] = useState(false);

  const createFromHDPathHandler = async () => {
    setIsAccountCreating(true);
    const newAccount = await addAccountFromHDPath(path);
    setIsAccountCreating(false);
    setAccount(newAccount);
    Alert.alert('Account Created');
  };

  return (
    <ScrollView style={{ marginTop: 24, paddingHorizontal: 24 }}>
      <View style={{ marginTop: 24, marginBottom: 30 }}>
        <Text variant="bodyLarge">
          <Text style={{ fontWeight: '700' }}>Enter the HD Path: </Text>
        </Text>
      </View>
      <TextInput
        mode="outlined"
        onChangeText={text => setPath(text)}
        value={path}
      />
      <View style={{ marginTop: 20, width: 200, alignSelf: 'center' }}>
        <Button
          mode="contained"
          onPress={createFromHDPathHandler}
          loading={isAccountCreating}>
          {isAccountCreating ? 'Adding' : 'Add Account'}
        </Button>
      </View>
      <View style={{ marginTop: 24 }}>
        {account && (
          <>
            <Text variant="bodyLarge">
              <Text style={{ fontWeight: '700' }}>Address: </Text>
              {account.address}
            </Text>
            <Text variant="bodyLarge">
              <Text style={{ fontWeight: '700' }}>Public Key: </Text>
              {account.pubKey}
            </Text>
          </>
        )}
      </View>
    </ScrollView>
  );
};

export default HDPath;
