import React, {useState, useEffect} from 'react';
import { SDK } from 'rm-sdk/build/';
import { Environment } from 'rm-sdk/build/types';
import { Web3Provider } from '@ethersproject/providers';
import { ApproveToken } from './approveToken';

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

  marketId: string;
  coverage: string;
}

export function ApproveMarketToken(props: IProps) {
  const sdk = new SDK(props.environment || Environment.EthereumMainnet);
  const [token, setToken] = useState('');
  const [approveFor, setApproveFor] = useState('');
  const [minApprovedAmount] = useState('0');
  const [noMarketFound, setNoMarketFound] = useState(false);

  useEffect(() => {
    checkAllowance();
  }, [props.provider, props.marketId, props.coverage]);

  async function checkAllowance() {
    if (props.provider && props.marketId && props.coverage) {
      try {
        const market = await sdk.getMarketById(props.marketId);

        if (!market) {
          setNoMarketFound(true);
        }

        setToken(market.premiumToken);
        setApproveFor(market.product.id);
      } catch (e) {
        console.error(e);
      }
    }
  }

  return <div>
    {
      noMarketFound && <div className="wizard-step-error">Specified market was not found</div>
    }
    { !noMarketFound &&
      <ApproveToken
        provider={props.provider}
        environment={props.environment}
        onFinish={props.onFinish}

        token={token}
        approveFor={approveFor}
        minApprovedAmount={minApprovedAmount}
      />
    }
  </div>;
}