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

import Web3 from 'web3';
import { WagmiConfig, createClient, configureChains, mainnet, useConnect, useAccount, useDisconnect } from 'wagmi'

import { MetaMaskConnector } from 'wagmi/connectors/metaMask'
import { publicProvider } from 'wagmi/providers/public'

const web3 = new Web3(Web3.givenProvider);

import Airdrop from "./Airdrop.json";

const airdropAddress = "0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512";
const airdropContract = new web3.eth.Contract(Airdrop.abi as any, airdropAddress);

const { chains, provider, webSocketProvider } = configureChains([mainnet], [publicProvider()]);

const wagmiClient = createClient({
  autoConnect: true,
  connectors: [
    new MetaMaskConnector({ chains }),
  ],
  provider,
  webSocketProvider,
})


function Profile() {
  const { connect, connectors, error, isLoading, pendingConnector } =
    useConnect()

    const { address, connector, isConnected } = useAccount()
    const { disconnect } = useDisconnect()

    if (isConnected) {
        const connectorName = connector?.name || "unknown connector";
    return (
      <div>
        <div>Connected to {connectorName} address: {address}</div>
        <button onClick={(_evt) => disconnect() }>Disconnect</button>
      </div>
    )
  }

  return (
    <div>
      <div>Connect to Airdrop App</div>
      {connectors.map((connector) => (
        <button
          disabled={!connector.ready}
          key={connector.id}
          onClick={() => connect({ connector })}
        >
          {connector.name}
          {!connector.ready && ' (unsupported)'}
          {isLoading &&
            connector.id === pendingConnector?.id &&
            ' (connecting)'}
        </button>
      ))}
 
      {error && <div>{error.message}</div>}
    </div>
  )
}



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

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

    const save = () => {
        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("");
    }

    var num;
    if (isNaN(numTokens) || numTokens < 0) {
        num = 0;
    } else {
        num = numTokens;
    }

    return (
    <div>
        <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>
        <div>
            Number of tokens:
            <input type="numeric" value={num} onChange={ (evt) => setNumTokens(parseInt(evt.target.value)) }></input>
        </div>
    </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([]);
    const { address: ownerAddress } = useAccount()

    async function performAirdrop() {
        console.log("Performing airdrop");

        console.log(airdropContract.methods);

        const allowance = await airdropContract.methods.allowance(ownerAddress, airdropAddress).call({ from: ownerAddress });
        console.log(`Allowance: ${allowance}`);


    }

  return (
    <WagmiConfig client={wagmiClient}>
    <div className="App">
        <Profile/>

        <h1>Airdrop App</h1>

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

    </div>
    </WagmiConfig>
  );
}

export default App;
