import React, {useState} from 'react';
import logo from './logo.svg';
import './App.css';

import Web3 from 'web3';

interface AddressesProps {
    addressList: string[];
    setAddressListFn: any;
}

function Addresses(props: AddressesProps) {
    const [inputState, setInputState] = useState("");
    const [errorText, setErrorText] = useState("");
    const { setAddressListFn, addressList } = props;

    const save = () => {
        console.log(inputState);
        //TODO check if correct address format
        if (!Web3.utils.isAddress(inputState)) {
            setErrorText("Invalid ETH address");
            return;
        }
        setErrorText("");

        const checksumAddr = Web3.utils.toChecksumAddress(inputState);

        if (addressList.includes(checksumAddr)) {
            //Do nothing
        } else {
            setAddressListFn([...addressList, checksumAddr]);
        }
        setInputState("");
    }
    return (
            <div>
            <input id="address" value={inputState} onChange={ (evt) => setInputState(evt.target.value) } ></input>
            <div className="addressError">{errorText}</div>
            <button onClick={save}>Add address</button>
            </div>
           );
}

interface AddressListProps {
    addressList: string[];
};

function AddressList({addressList}: AddressListProps) {

    const addresses = addressList.length == 0 ?
    <p>No addresses specified yet</p> :
    addressList.map((addr: string) => <div key={addr} className="addressItem">{addr}</div>);
    return (
        <div>
            <h2>Addresses to airdrop to: </h2>
            { addresses }
        </div>
    )
}

function App() {
    const [addressList, setAddressList] = useState([]);

  return (
    <div className="App">

        <h1>Airdrop App</h1>

      <p>Add an address to airdrop to:</p>
      <Addresses addressList={addressList} setAddressListFn={setAddressList}/>
      <button disabled={addressList.length == 0}>Perform Airdrop!</button>
      <AddressList addressList={addressList} />

    </div>
  );
}

export default App;
