import React, {useState, useEffect} from 'react';
import {
  Button,
} from '../../components/ui/Widget';
import { Environment } from 'rm-sdk/build/types';
import BigNumber from "bignumber.js";
import { Web3Provider } from '@ethersproject/providers';
import { ActivateProtectionView } from '../RMWidget/ActivateProtectionView';
import { QuoteLoader} from '../../helpers/quote-loader';
import { toSuffixFormat } from '../../utils/configureFormats';

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

  marketId: string;
  coverage: string;
}

export function ActivateMarketProtection(props: IProps) {
  const [quoteLoader] = useState(new QuoteLoader(props.environment || Environment.EthereumMainnet));
  const [desiredCover, setDesiredCover] = useState(props.coverage);
  const [topUpValue, setTopUpValue] = useState<BigNumber>();
  const [isPremiumTokenNotEnough, setPremiumTokenNotEnough] = useState<boolean|null>(null);
  const [total, setTotal] = useState<BigNumber>();
  const [duration, setDuration] = useState(180);
  const [isLoading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);

    quoteLoader.load(
      props.provider,
      duration,
      props.marketId,
      desiredCover,
    ).then(r => {
      setLoading(false);

      if (!r) {
        return;
      }

      updateValues();
    });
  }, [props.provider, props.marketId, props.coverage]);

  useEffect(() => {
    setLoading(true);

    quoteLoader.calcQuote(
      props.provider,
      desiredCover,
      duration,
    ).then(r => {
      setLoading(false);

      if (!r) {
        return;
      }

      updateValues();
    });
  }, [desiredCover]);

  useEffect(() => {
    checkBalance();
  }, [props.provider, total]);

  function updateValues() {
    setTopUpValue(quoteLoader.topUpValue);
    setTotal(quoteLoader.topUpValue && quoteLoader.topUpValue.plus(quoteLoader.minDeposit || 0));

    if (quoteLoader.monthlyQuote?.isZero() && duration !== 0) {
      setDuration(0);
    }
  }

  async function checkBalance() {
    const b = await quoteLoader.getPremiumTokenBalance(
      props.provider
    );

    if (!b) {
      return;
    }

    setPremiumTokenNotEnough(new BigNumber(b).lt(total || 0));
  }

  async function handleBuyPolicy() {
    setLoading(true);

    try {
      const tx = await quoteLoader.buyPolicy(
        props.provider,
        desiredCover,
        total?.toFixed() || '0',
      );

      if (tx) {
        await tx.wait(1);

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

    setLoading(false);
  }

  function handleDesiredCoverChanged(value: string): boolean {
    if (Number.isFinite(+value) && +value > 0) {
      setDesiredCover(value);

      return true;
    }

    return false;
  }

  function handleDurationChanged(value: number): boolean {
    if (quoteLoader.minDeposit && quoteLoader.monthlyQuote) {
      const topUp = quoteLoader.monthlyQuote.isZero() ? new BigNumber(0) : quoteLoader.monthlyQuote.times(value).div(30);

      setTopUpValue(topUp);
      setTotal(quoteLoader.minDeposit.plus(topUp));
      setDuration(+value);

      return true;
    }

    return false;
  }

  function handleTopUpValueChanged(value: string): boolean {
    if (Number.isFinite(+value) && quoteLoader.minDeposit && quoteLoader.monthlyQuote && new BigNumber(value).gte(0)) {
      const t = new BigNumber(value)
        .toFixed(quoteLoader.premiumToken?.decimals || 2, BigNumber.ROUND_UP);

      quoteLoader.updateTopUpValue(t);

      setTopUpValue(quoteLoader.topUpValue);
      setTotal(quoteLoader.quote);
      setDuration(quoteLoader.duration ?? 0);

      return true;
    }

    return false;
  }

  return <div>
    <div className='wizard-step-header'></div>
    <div>
      <ActivateProtectionView
        capitalTokenInfo={quoteLoader.capitalToken}
        insuredTokenInfo={quoteLoader.insuredToken}
        premiumTokenInfo={quoteLoader.premiumToken}
        topUpValue={topUpValue}
        desiredCover={desiredCover}
        handleDesiredCoverChanged={handleDesiredCoverChanged}
        handleTopUpValueChanged={handleTopUpValueChanged}
        handleDurationChanged={handleDurationChanged}
        minDeposit={quoteLoader.minDeposit}
        rate={quoteLoader.rate?.toFixed(2, BigNumber.ROUND_UP)}
        monthPrice={quoteLoader.monthlyQuote}
        duration={duration}
        totalDeposit={quoteLoader.quote}
      />
    </div>

    {
      isPremiumTokenNotEnough &&
      <div className='error'>You don't have enough premium token to activate protection.</div>
    }

    {
      !isPremiumTokenNotEnough && <Button type='button' disabled={isLoading || topUpValue === undefined} onClick={handleBuyPolicy}>Activate &amp; top-up {
        quoteLoader.premiumToken && `${toSuffixFormat(quoteLoader.quote, 2, BigNumber.ROUND_UP)} ${quoteLoader.premiumToken.symbol}`}</Button>
    }
  </div>;
}