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

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

const HDPath = ({
  updateAccounts,
  updateIndex,
  hideDialog,
}: {
  updateIndex: (index: number) => void;
  updateAccounts: (account: Account) => void;
  hideDialog: () => void;
}) => {
  const [path, setPath] = useState<string>('');
  const [isAccountCreating, setIsAccountCreating] = useState(false);

  const createFromHDPathHandler = async () => {
    setIsAccountCreating(true);
    const newAccount = await addAccountFromHDPath(path);
    setIsAccountCreating(false);

    if (newAccount) {
      updateAccounts(newAccount);
      updateIndex(newAccount.counterId);
      hideDialog();
    }
  };

  return (
    <ScrollView style={{ marginTop: 24, paddingHorizontal: 24 }}>
      <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>
    </ScrollView>
  );
};

export default HDPath;
