import type { ExtendedChain } from '@openocean.finance/widget-sdk'
import { ChainType, config, getChains } from '@openocean.finance/widget-sdk'
import { useQuery } from '@tanstack/react-query'
import { useCallback } from 'react'
import { useWidgetConfig } from '../providers/WidgetProvider/WidgetProvider.js'
import { isItemAllowed } from '../utils/item.js'
import { CoinKey } from '../index.js'
import { DEFAULT_CHAIN_IDS } from '../config/defaultChainIds.js';

export type GetChainById = (
  chainId?: number,
  chains?: ExtendedChain[]
) => ExtendedChain | undefined

const supportedChainTypes: ChainType[] = [ChainType.EVM, ChainType.SVM, ChainType.UTXO]

export const useAvailableChains = (chainTypes?: ChainType[]) => {
  const { chains } = useWidgetConfig()
  // const { providers } = useHasExternalWalletProvider();
  const { data, isLoading } = useQuery({
    queryKey: [
      'chains',
      // providers,
      chains?.types,
      chains?.allow,
      chains?.deny,
      chains?.from,
      chains?.to,
    ] as const,
    queryFn: async ({ queryKey: [, chainTypesConfig] }) => {
      const chainTypesRequest = supportedChainTypes
        // providers.length > 0 ? providers : supportedChainTypes
        .filter((chainType) => isItemAllowed(chainType, chainTypesConfig))

      let availableChains = await getChains()
      // reset solana chain id
      const solanaChain = availableChains.find((chain) => chain.key === 'sol')
      if (solanaChain) {
        solanaChain.chainType = ChainType.SVM;
        solanaChain.id = 1151111081099710;
      }
      // allow chains "starknet","aptos","near","ont","sui",
      const allowedChainsIds = chains?.allow?.length ? chains.allow : DEFAULT_CHAIN_IDS;
      const allowedChains = availableChains.filter((chain) => {
        if (allowedChainsIds.indexOf(chain.id) >= 0) {
          return true
        }
        return false
      })
      /*
      allowedChains.push({
        "key":"eth",
        "chainType":ChainType.EVM,
        "name":"Ethereum",
        "coin":CoinKey.WETH,
        "id":1,
        "mainnet":true,
        "logoURI":"https://raw.githubusercontent.com/lifinance/types/main/src/assets/icons/chains/ethereum.svg",
        "tokenlistUrl":"https://gateway.ipfs.io/ipns/tokens.uniswap.org",
        "multicallAddress":"0xcA11bde05977b3631167028862bE2a173976CA11",
        "relayerSupported":false,
        "metamask":{
          "chainId":"0x1",
          "blockExplorerUrls":["https://etherscan.io/"],
          "chainName":"Ethereum Mainnet",
          "nativeCurrency":{
            "name":"ETH",
            "symbol":"ETH",
            "decimals":18
          },
          "rpcUrls":[
            "https://ethereum-rpc.publicnode.com",
            "https://eth.drpc.org"
          ]
        },
        "nativeToken":{
          "address":"0x0000000000000000000000000000000000000000",
          "chainId":1,"symbol":
          "ETH","decimals":18,
          "name":"ETH",
          "coinKey":"ETH",
          "logoURI":"https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2/logo.png",
          "priceUSD":"3804.11"
        },
        "diamondAddress":"0x1231DEB6f5749EF6cE6943a275A1D3E7486F4EaE",
        "permit2":"0x000000000022D473030F116dDEE9F6B43aC78BA3",
        "permit2Proxy":"0x89c6340B1a1f4b25D36cd8B063D49045caF3f818"
      })
      */
      config.setChains(allowedChains)
      return allowedChains
    },
    refetchInterval: 300_000,
    staleTime: 300_000,
  })

  const getChainById: GetChainById = useCallback(
    (chainId?: number, chains: ExtendedChain[] | undefined = data) => {
      if (!chainId) {
        return
      }
      const chain = chains?.find((chain) => chain.id === chainId)
      return chain
    },
    [data]
  )

  return {
    chains: data,
    getChainById,
    isLoading,
  }
}
