import { JsonRpcProvider } from "@ethersproject/providers";
import { providers } from "ethers";
import { useState } from "react";
import { useAccount, usePublicClient } from "wagmi";

import useActiveChainId from "./useActiveChainId";

const useProviderOrSigner = (_withSignerIfPossible = true) => {
  const [providerCache, setProviderCache] = useState<JsonRpcProvider | undefined>(undefined);
  const [chainIdCache, setChainCache] = useState<number | undefined>(undefined);
  const { chainId } = useActiveChainId();
  const publicClient = usePublicClient({ chainId });
  const { address } = useAccount();
  let provider;
  if (!providerCache || chainId !== chainIdCache) {
    provider = new providers.JsonRpcProvider(publicClient.transport.transports[0].value.url);
    setProviderCache(provider);
    setChainCache(chainId);
  } else {
    provider = providerCache;
  }
  const signer = provider?.getSigner(address);
  return signer;
  // return useMemo(() => (withSignerIfPossible && address && isConnected && signer ? signer : provider), [address, isConnected, provider, signer, withSignerIfPossible]);
};

export default useProviderOrSigner;
