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

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

import { AccountsProps, StackParamsList, Account } from '../types';
import { addAccount } from '../utils';

const Accounts: React.FC<AccountsProps> = ({
  network,
  accounts,
  updateAccounts,
  currentIndex,
  updateIndex,
}) => {
  const navigation =
    useNavigation<NativeStackNavigationProp<StackParamsList>>();

  const [expanded, setExpanded] = useState(false);

  const handlePress = () => setExpanded(!expanded);

  const addAccountHandler = async () => {
    const newAccount = await addAccount(network);
    newAccount && updateAccounts(newAccount);
    updateIndex(selectedAccounts[selectedAccounts.length -1].id);
  };

  let selectedAccounts: Account[] = [];

  if (network === 'eth') {
    selectedAccounts = accounts.ethAccounts;
  }
  if (network === 'cosmos') {
    selectedAccounts = accounts.cosmosAccounts;
  }

  return (
    <View>
      <List.Accordion
        title={`Account ${currentIndex + 1}`}
        expanded={expanded}
        onPress={handlePress}>
        {selectedAccounts &&
          selectedAccounts.map((account) => (
            <List.Item
              key={account.id}
              title={`Account ${account.id + 1}`}
              onPress={() => {
                updateIndex(account.id);
                setExpanded(false);
              }}
            />
          ))}
      </List.Accordion>
      <View style={{ alignItems: 'center', marginTop: 24 }}>
        <Button mode="contained" onPress={addAccountHandler}>
          Add Account
        </Button>
      </View>
      <View style={{ marginTop: 24 }}>
        <Text variant="bodyLarge">
          <Text style={{ fontWeight: '700' }}>Address: </Text>
          {selectedAccounts &&
            selectedAccounts[currentIndex] &&
            selectedAccounts[currentIndex].address}
        </Text>
        <Text variant="bodyLarge">
          <Text style={{ fontWeight: '700' }}>Public Key: </Text>
          {selectedAccounts &&
            selectedAccounts[currentIndex] &&
            selectedAccounts[currentIndex].pubKey}
        </Text>
      </View>
      <View style={{ alignItems: 'center', marginTop: 24 }}>
        <Button
          mode="contained"
          onPress={() => {
            navigation.navigate('SignMessage', {
              selectedNetwork: network,
              accountInfo: selectedAccounts[currentIndex],
            });
          }}>
          Sign Message
        </Button>
      </View>
    </View>
  );
};

export default Accounts;
