import { useEffect, useState } from 'react';
import { useSDK } from '@metamask/sdk-react';
import { Web3 } from 'web3';
import Button from 'react-bootstrap/Button';
// import './App.css';
import DAOArtifact from './assets/DAO.json';
// import work1Artifact from './assets/Work1.json';

const contracts = {
  '0x539': { // Hardhat
    DAO: '0x7209aa5b0B91700615bA982e4E4F1Eb967E31cf1',
    Work1: '0x4a3f03f50b542BD27DbcaDAF9A3d608AE4f5AACc',
  },
  '0xaa36a7': { // Sepolia
    DAO: '0x8d914D38dD301FC4606f5aa9fEcF8A76389020d3',
    Work1: '0x050C420Cc4995B41217Eba1B54B82Fd5687e9139',
  },
};

function App() {
  const {
    sdk, connected, provider, chainId, account, balance,
  } = useSDK();

  const [DAO, setDAO] = useState();
  // const [work1, setWork1] = useState();
  // const [work1Price, setWork1Price] = useState();
  const [balanceEther, setBalanceEther] = useState();
  const [reputation, setReputation] = useState();
  const [totalReputation, setTotalReputation] = useState();
  const [validationPoolCount, setValidationPoolCount] = useState();
  const [latestPoolIndex, setLatestPoolIndex] = useState();
  const [votePasses, setVotePasses] = useState();

  // const watchReputationToken = useCallback(async () => {
  //   await provider.request({
  //     method: 'wallet_watchAsset',
  //     params: {
  //       type: 'ERC20',
  //       options: {
  //         address: DAOAddress,
  //       },
  //     },
  //   });
  // }, [provider]);

  useEffect(() => {
    if (!provider || !chainId || !account) return;
    if (!contracts[chainId]) return;
    const web3 = new Web3(provider);
    const DAOContract = new web3.eth.Contract(DAOArtifact.abi, contracts[chainId].DAO);
    // const work1Contract = new web3.eth.Contract(work1Artifact.abi, contracts[chainId].Work1);

    // const fetchPrice = async () => {
    //   const priceWei = await work1Contract.methods.price().call();
    //   setWork1Price(web3.utils.fromWei(priceWei, 'ether'));
    // };

    const fetchReputation = async () => {
      console.log(`fetchReputation, account: ${account}`);
      setReputation(await DAOContract.methods.balanceOf(account).call());
      setTotalReputation(await DAOContract.methods.totalSupply().call());
    };

    const fetchValidationPoolCount = async () => {
      setValidationPoolCount(await DAOContract.methods.validationPoolCount().call());
    };

    // fetchPrice();
    fetchReputation();
    fetchValidationPoolCount();
    // setWork1(work1Contract);
    setDAO(DAOContract);

    DAOContract.events.ValidationPoolInitiated({ fromBlock: 'latest' }).on('data', (event) => {
      console.log('event: validation pool initiated', event);
      setLatestPoolIndex(event.returnValues.poolIndex);
      fetchValidationPoolCount();
    });

    DAOContract.events.ValidationPoolResolved({ fromBlock: 'latest' }).on('data', (event) => {
      console.log('event: validation pool resolved', event);
      setVotePasses(event.returnValues.votePasses);
      fetchReputation();
    });
  }, [provider, account, chainId]);

  useEffect(() => {
    if (!provider || balance === undefined) return;
    const web3 = new Web3(provider);
    setBalanceEther(web3.utils.fromWei(balance, 'ether'));
  }, [provider, balance]);

  const connect = async () => {
    try {
      await sdk?.connect();
    } catch (err) {
      console.warn('failed to connect..', err);
    }
  };

  const disconnect = async () => {
    try {
      sdk?.terminate();
    } catch (err) {
      console.warn('failed to disconnect..', err);
    }
  };

  const initiateValidationPool = async () => {
    const poolDuration = 0;
    await DAO.methods.initiateValidationPool(account, poolDuration).send({
      from: account,
      gas: 1000000,
      value: 100,
    });
  };

  const evaluateOutcome = async () => {
    await DAO.methods.evaluateOutcome(latestPoolIndex).send({
      from: account,
      gas: 1000000,
    });
  };

  // const stakeAvailability = async () => { }

  // const requestWork = async () => {
  //   work1.events.WorkAssigned(() => {
  //     console.log('event callback');
  //   });
  //   await work1.methods.requestWork().send({
  //     from: account,
  //     gas: 1000000,
  //   });
  // };

  return (
    <>
      {!connected && <Button onClick={() => connect()}>Connect</Button>}

      {connected && (
        <>
          <div>
            {!contracts[chainId] && (
            <div>
              Please switch MetaMask to Sepolia testnet!
            </div>
            )}
            <div>
              {chainId && `Chain ID: ${chainId}`}
            </div>
            <div>
              {`Account: ${account}`}
            </div>
            <div>
              {`Balance: ${balanceEther} ETH`}
            </div>
            <div>
              {`Your REP: ${reputation}`}
            </div>
            <div>
              {`Total REP: ${totalReputation}`}
            </div>
            <Button onClick={() => disconnect()}>Disconnect</Button>
          </div>
          <div>
            {`Validation Pool Count: ${validationPoolCount}`}
          </div>
          <div>
            <Button onClick={() => initiateValidationPool()}>Initiate Validation Pool</Button>
          </div>
          <div>
            <Button onClick={() => evaluateOutcome()}>Evaluate Outcome</Button>
          </div>
          <div>
            {`Outcome: ${votePasses}`}
          </div>
          <div>
            { /* `Work1 Price: ${work1Price} ETH` */ }
          </div>
          <div>
            { /* <Button onClick={() => requestWork()}>Request Work</Button> */ }
          </div>
        </>
      )}
    </>
  );
}

export default App;
