import React, {useState, useEffect} from 'react';
import {
  Button,
  Spinner,
} from '../../components/ui/Widget';
import { SDK } from 'rm-sdk/build/';
import { Environment } from 'rm-sdk/build/types';
import BigNumber from "bignumber.js";
import { Web3Provider } from '@ethersproject/providers';

interface IProps {
  environment: Environment | string;
  provider: Web3Provider;
  onFinish: (status: boolean) => void;

  token: string;
  approveFor: string;
  minApprovedAmount: string;
}

export function ApproveToken(props: IProps) {
  const sdk = new SDK(props.environment || Environment.EthereumMainnet);
  const [isLoading, setLoading] = useState(false);

  useEffect(() => {
    checkAllowance();
  }, [props.provider, props.approveFor, props.token]);

  async function checkAllowance() {
    if (props.provider && props.approveFor && props.token) {
      setLoading(true);
      try {
        const account = (await props.provider.listAccounts())[0];
        const a = new BigNumber(await sdk.getTokenAllowance(
          props.token,
          account,
          props.approveFor,
          props.provider,
        ));

        if (a.gt(0) && a.gte(props.minApprovedAmount)) {
          props.onFinish(true);
        }
      } catch (e) {
        console.error(e);
      }

      setLoading(false);
    } else {
      setLoading(true);
    }
  }

  async function handleApprove() {
    try {
      setLoading(true);
      const tx = await sdk.setTokenAllowance(
        props.token,
        props.approveFor,
        props.provider,
        props.minApprovedAmount === '0' ?  undefined : props.minApprovedAmount,
      );

      await tx.wait(1);

      props.onFinish(true);
    } catch(e) {
      console.error(e);
    }

    setLoading(false);
  }

  return <div className={'wizard-step-container'}>
    {
      !isLoading && <div className="spinner-container">Checking token allowance <Spinner /> </div>
    }
    {
      !isLoading && <Button
        onClick={handleApprove}
        color='#ff975b'
        background={'#fff'}>
          Approve
      </Button>
    }
  </div>;

}