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

import { NetworkDropdownProps } from '../types';
import styles from '../styles/stylesheet';
import { useAccounts } from '../context/AccountsContext';

const NetworkDropdown = ({ updateNetwork }: NetworkDropdownProps) => {
  const [expanded, setExpanded] = useState<boolean>(false);
  const [selectedNetwork, setSelectedNetwork] = useState<string>('Ethereum');

  const { networksData } = useAccounts();

  const networks = useMemo(() => {
    const defaultNetworks = [
      { value: 'eth', chainId: 'eip155:1', displayName: 'Ethereum' },
      { value: 'cosmos', chainId: 'cosmos:cosmoshub-4', displayName: 'Cosmos' },
    ];

    networksData.forEach(network => {
      defaultNetworks.push({
        value: network.networkType,
        chainId: network.chainId,
        displayName: network.networkName,
      });
    });

    return defaultNetworks;
  }, [networksData]);

  const handleNetworkPress = (network: string, displayName: string) => {
    updateNetwork(network);
    setSelectedNetwork(displayName);
    setExpanded(false);
  };

  return (
    <View style={styles.networkDropdown}>
      <List.Accordion
        title={selectedNetwork}
        expanded={expanded}
        onPress={() => setExpanded(!expanded)}>
        {networks.map(network => (
          <List.Item
            key={network.chainId}
            title={network.displayName}
            onPress={() =>
              handleNetworkPress(network.value, network.displayName)
            }
          />
        ))}
      </List.Accordion>
    </View>
  );
};

export { NetworkDropdown };
