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

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

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

  const handleChange = (key: keyof PathState, value: string) => {
    setPath({
      ...path,
      [key]: value.replace(/[^0-9]/g, ''), // Allow only numeric characters
    });
  };

  const createFromHDPathHandler = async () => {
    setIsAccountCreating(true);

    const hdPath =
      pathCode +
      `${path.firstNumber}'/${path.secondNumber}/${path.thirdNumber}`;

    try {
      const newAccount = await addAccountFromHDPath(hdPath);
      if (newAccount) {
        updateAccounts(newAccount);
        updateIndex(newAccount.counterId);
        hideDialog();
      }
    } catch (error) {
      console.error('Error creating account:', error);
    } finally {
      setIsAccountCreating(false);
    }
  };

  return (
    <ScrollView style={styles.container}>
      <View style={styles.rowContainer}>
        <Text style={styles.text}>{pathCode}</Text>
        <TextInput
          keyboardType="numeric"
          mode="outlined"
          onChangeText={text => handleChange('firstNumber', text)}
          value={path.firstNumber}
          style={styles.textInput}
          maxLength={1}
        />
        <Text style={styles.text}>'/</Text>
        <TextInput
          keyboardType="numeric"
          mode="outlined"
          onChangeText={text => handleChange('secondNumber', text)}
          value={path.secondNumber}
          style={styles.textInput}
          maxLength={1}
        />
        <Text style={styles.text}>/</Text>
        <TextInput
          keyboardType="numeric"
          mode="outlined"
          onChangeText={text => handleChange('thirdNumber', text)}
          value={path.thirdNumber}
          style={styles.textInput}
          maxLength={1}
        />
      </View>
      <View style={styles.buttonContainer}>
        <Button
          mode="contained"
          onPress={createFromHDPathHandler}
          loading={isAccountCreating}>
          {isAccountCreating ? 'Adding' : 'Add Account'}
        </Button>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    marginTop: 24,
    paddingHorizontal: 8,
  },
  rowContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  text: {
    color: 'black',
    fontSize: 18,
    padding: 10,
  },
  textInput: {
    flex: 1,
  },
  buttonContainer: {
    marginTop: 20,
    width: 200,
    alignSelf: 'center',
  },
});

export default HDPath;
