import { Contract } from "@ethersproject/contracts";
import { JsonRpcProvider, JsonRpcSigner } from "@ethersproject/providers";
import { Signer } from "ethers";
import { useMemo } from "react";
import { useNetwork } from "wagmi";

import { Erc20 } from "../payTypes/Erc20";
import addresses from "../utils/contracts";
import Erc20ABI from "../utils/erc20.json";
import { getAddress } from "../utils/util";
import useProviderOrSigner from "./useProviderOrSigner";

export const getErc20Contract = (address: `0x${string}`, signer?: Signer | JsonRpcProvider | JsonRpcSigner) => {
  return new Contract(address, Erc20ABI, signer) as Erc20;
};
export const useERC20 = (address: string, withSignerIfPossible = true) => {
  const providerOrSigner = useProviderOrSigner(withSignerIfPossible);
  return useMemo(() => getErc20Contract(address as `0x${string}`, providerOrSigner), [address, providerOrSigner]);
};

export const getUsdtAddress = (chainId?: number) => {
  return getAddress(addresses.usdt, chainId);
};

export const useUsdtERC20 = (withSignerIfPossible = true) => {
  const { chain } = useNetwork();
  const address = getUsdtAddress(chain?.id);
  const providerOrSigner = useProviderOrSigner(withSignerIfPossible);
  return useMemo(() => getErc20Contract(address as `0x${string}`, providerOrSigner), [address, providerOrSigner]);
};
