/* eslint-disable no-console */
import { BigNumber } from "bignumber.js";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useNetwork } from "wagmi";

import { useERC20 } from "./useContract";

function useTokenAllowance(
  token: { amount: BigNumber | null; address: string },
  owner?: string,
  spender?: string,
  hash?: string
): BigNumber | undefined {
  const { chain } = useNetwork();
  const contract = useERC20(token.address, false);
  const [allowance, setAllowance] = useState<BigNumber>(new BigNumber(0));
  const getAllowance = useCallback(async () => {
    try {
      const result = await contract.allowance(owner as string, spender as string);
      setAllowance(new BigNumber(result.toString()));
    } catch (error) {
      console.warn(error);
    }
  }, [contract, spender]);
  useEffect(() => {
    getAllowance();
  }, [spender, token.address, hash, chain?.id]);
  return useMemo(() => (token && allowance ? allowance : undefined), [token, allowance]);
}

export default useTokenAllowance;
