import React, { useState, useEffect } from 'react'
import { Flex, Button, Modal, Image } from '@pancakeswap/uikit'
import styled from 'styled-components'
import { useTranslation } from 'contexts/Localization'
import { useAccount } from 'state/userInfo/hooks'
import { fetchReferralUserAllowances } from 'state/referral'
import { useERC20 } from 'hooks/useContract'
import { getAddress } from 'utils/addressHelpers'
import useToast from 'hooks/useToast'
import { checkBuyResult } from 'services/referral'
import useRefresh from 'hooks/useRefresh'
import tokens from 'config/constants/tokens'
import { useCheckTokenBalance, useApproveReferral, useBuyTransaction } from '../hooks'

// interface BuyActionsProps {

// }

const Btn = styled(Button)`
  width: 50%;
  margin: 20px auto 0px auto;
  border-radius: 50px;
  background: linear-gradient(180deg, #7be0fc 0%, #ac7bf1 100%);
  border: none;
`
const BuyActions: React.FC = () => {
  const { t } = useTranslation()
  const account = useAccount()
  const [allowanceList, setAllowanceList] = useState({ usdt: 0, hcc: 0 })
  const usdtContract = useERC20(getAddress(tokens.usdt.address))
  const [loading, setLoading] = useState(false)
  const [txId, setTxId] = useState()
  const { toastSuccess } = useToast()
  const { fastRefresh } = useRefresh()
  const hccContract = useERC20(getAddress(tokens.hcc.address))
  const { onApprove: onUsdtApprove } = useApproveReferral(usdtContract)
  const { onApprove: onHccApprove } = useApproveReferral(hccContract)
  const buyTransaction = useBuyTransaction()
  const handleApprove = async (approve) => {
    try {
      setLoading(true)
      await approve()
      setLoading(false)
      getAllowances()
    } catch (e) {
      console.error(e)
    }
  }
  const getAllowances = async () => {
    const allowances = await fetchReferralUserAllowances(account)
    setAllowanceList({
      usdt: allowances.usdt,
      hcc: allowances.hcc,
    })
  }
  const handleBuy = async () => {
    await buyTransaction()
  }
  const getTransactionResult = async () => {
    const res = await checkBuyResult({ tx: txId })
    if (res?.success) {
      setLoading(false)
      setTxId(undefined)
      toastSuccess('Buy Success')
    }
  }
  useEffect(() => {
    if (txId && loading) {
      getTransactionResult()
    }
  }, [fastRefresh])

  useEffect(() => {
    if (account) {
      getAllowances()
    } else {
      setAllowanceList({ usdt: 0, hcc: 0 })
    }
  }, [])

  return (
    <Flex>
      {!allowanceList.usdt && (
        <Btn
          disabled={loading}
          onClick={() => {
            handleApprove(onUsdtApprove)
          }}
        >
          {t('Approve %coin% Contract', { coin: 'usdt' })}
        </Btn>
      )}

      {!allowanceList.hcc && (
        <Btn
          disabled={loading}
          onClick={() => {
            handleApprove(onHccApprove)
          }}
        >
          {t('Approve %coin% Contract', { coin: 'hcc' })}
        </Btn>
      )}
      {allowanceList?.usdt && allowanceList.hcc ? <Btn onClick={handleBuy}>{t('Buy It Now')}</Btn> : null}
    </Flex>
  )
}

export default BuyActions
