import React, { useState } from 'react';
import { ScrollView, View, Text } from 'react-native';
import { Button, TextInput } from 'react-native-paper';
import { addAccountFromHDPath } from '../utils/Accounts';
import { Account } from '../types';

const HDPath = ({
  pathCode,
  updateAccounts,
  updateIndex,
  hideDialog,
}: {
  pathCode: string;
  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 hdPath = pathCode + path;
    const newAccount = await addAccountFromHDPath(hdPath);
    setIsAccountCreating(false);

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

  return (
    <ScrollView style={{ marginTop: 24, paddingHorizontal: 24 }}>
      <View style={{ flexDirection: 'row', alignItems: 'center' }}>
        <Text style={{ color: 'black', fontSize: 18, padding: 10 }}>
          {pathCode}
        </Text>
        <TextInput
          mode="outlined"
          onChangeText={text => setPath(text)}
          value={path}
          style={{ flex: 1 }}
        />
      </View>
      <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;
