import { computed, ref } from 'vue'
import type { WalletType } from '@/stores/transfer'
import {
  involvesSpotTradingBridge,
  loadSpotTransferAssetContext,
  type SpotTransferAssetContext,
} from '@/utils/spotAsset'

export { involvesSpotTradingBridge }

export interface UseSpotTransferCoinOptions {
  /** 为 true 时加载后优先保持 initialSymbol（如 IDO 页默认 IBIT），不在列表则补入可选币种 */
  preferInitialSymbol?: boolean
}

export function useSpotTransferCoin(
  initialSymbol = 'USDT',
  options?: UseSpotTransferCoinOptions,
) {
  const preferred = (initialSymbol || 'USDT').trim().toUpperCase()
  const symbol = ref(preferred)
  const assetCtx = ref<SpotTransferAssetContext | null>(null)
  const assetsLoading = ref(false)

  const coinOptions = computed(() => assetCtx.value?.openCoins ?? [preferred || 'USDT'])

  async function loadAssets() {
    assetsLoading.value = true
    try {
      const ctx = await loadSpotTransferAssetContext()
      let coins = [...ctx.openCoins]
      if (options?.preferInitialSymbol && preferred) {
        if (!coins.includes(preferred)) {
          coins = [preferred, ...coins]
        }
        symbol.value = preferred
      } else if (!coins.includes(symbol.value)) {
        symbol.value = coins.includes('USDT') ? 'USDT' : coins[0]
      }
      assetCtx.value = { ...ctx, openCoins: coins }
    } finally {
      assetsLoading.value = false
    }
  }

  function availableFor(wallet: WalletType, sym: string): string {
    const key = sym.toUpperCase()
    if (wallet === 'SPOT_TRADING') {
      return assetCtx.value?.spotAvailable[key] ?? '0'
    }
    if (wallet === 'SPOT') {
      return assetCtx.value?.fundAvailable[key] ?? '0'
    }
    return '0'
  }

  return {
    symbol,
    assetCtx,
    assetsLoading,
    coinOptions,
    loadAssets,
    availableFor,
  }
}
