import { post } from '@/utils/request'
import { fetchStakingWalletBalance } from '@/api/staking'
import { parseFundWalletBalances } from '@/utils/spotAsset'

/** 质押划转当前仅支持 iBit */
export const STAKING_COIN_UNIT = 'IBIT'

export interface StakingAccountSnapshot {
  available: string
  locked: string
  /** 已释放总量（iBit 等原币，勿与 locked/frozenBalance 混淆） */
  released: string
  availableUsdt: string
  lockedUsdt: string
}

export interface WalletAccountRow {
  name: string
  balance?: string | number
  balanceUsdt?: string | number
  frozenBalance?: string | number
  frozenBalanceUsdt?: string | number
  currentCapital?: string | number
}

export function isStakingAccountName(name: string | undefined | null): boolean {
  if (!name) return false
  const n = name.trim()
  return n.includes('质押') || /staking/i.test(n)
}

export function pickStakingAccount(list: WalletAccountRow[] | undefined | null): WalletAccountRow | null {
  if (!list?.length) return null
  return list.find((a) => isStakingAccountName(a.name)) ?? null
}

/** 从 /swap/wallet-new/get 解析质押钱包可用/锁仓（原始数量，多为 iBit） */
export function parseStakingFromWalletGet(raw: unknown): StakingAccountSnapshot {
  const empty: StakingAccountSnapshot = {
    available: '0',
    locked: '0',
    released: '0',
    availableUsdt: '0',
    lockedUsdt: '0',
  }
  if (!raw || typeof raw !== 'object') return empty
  const r = raw as Record<string, unknown>
  const list = (r.accountInfoList ?? (r.data as Record<string, unknown> | undefined)?.accountInfoList) as
    | WalletAccountRow[]
    | undefined
  const row = pickStakingAccount(Array.isArray(list) ? list : [])
  if (!row) return empty
  const extra = row as unknown as Record<string, unknown>
  return {
    available: String(row.balance ?? '0'),
    locked: String(row.frozenBalance ?? extra.frozen_balance ?? '0'),
    released: String(extra.releasedTotal ?? extra.released_total ?? '0'),
    availableUsdt: String(row.balanceUsdt ?? extra.balance_usdt ?? '0'),
    lockedUsdt: String(row.frozenBalanceUsdt ?? extra.frozen_balance_usdt ?? '0'),
  }
}

/** 资金账户指定币种可用余额 */
export async function loadFundCoinBalance(coinUnit: string): Promise<string> {
  try {
    const raw = await post<unknown>('/uc/asset/wallet', {})
    const map = parseFundWalletBalances(raw)
    return map[coinUnit.toUpperCase()] ?? '0'
  } catch {
    return '0'
  }
}

function parseStakingWalletRow(raw: unknown): StakingAccountSnapshot {
  const empty: StakingAccountSnapshot = {
    available: '0',
    locked: '0',
    released: '0',
    availableUsdt: '0',
    lockedUsdt: '0',
  }
  if (!raw || typeof raw !== 'object') return empty
  const r = raw as Record<string, unknown>
  const row = (r.data && typeof r.data === 'object' ? r.data : r) as Record<string, unknown>
  const available = row.availableBalance ?? row.available_balance ?? row.balance
  const locked = row.lockedBalance ?? row.locked_balance ?? row.frozenBalance
  const released = row.releasedTotal ?? row.released_total
  const availableUsdt =
    row.availableBalanceUsdt ?? row.available_balance_usdt ?? row.balanceUsdt ?? row.balance_usdt
  const lockedUsdt =
    row.lockedBalanceUsdt ?? row.locked_balance_usdt ?? row.frozenBalanceUsdt ?? row.frozen_balance_usdt
  return {
    available: String(available ?? '0'),
    locked: String(locked ?? '0'),
    released: String(released ?? '0'),
    availableUsdt: String(availableUsdt ?? '0'),
    lockedUsdt: String(lockedUsdt ?? '0'),
  }
}

/** 总览展示：wallet-new 质押账户 balance / frozenBalance；划转可用：staking/wallet availableBalance */
export function applyStakingOverviewBalances(
  walletSnap: StakingAccountSnapshot,
  apiSnap: StakingAccountSnapshot | null,
): { overview: StakingAccountSnapshot; transferAvailable: string } {
  const overview: StakingAccountSnapshot = {
    available: walletSnap.available,
    locked: walletSnap.locked,
    released: walletSnap.released,
    availableUsdt: walletSnap.availableUsdt,
    lockedUsdt: walletSnap.lockedUsdt,
  }
  let transferAvailable = walletSnap.available
  if (apiSnap) {
    transferAvailable = apiSnap.available
    if (Number(overview.available) === 0 && Number(apiSnap.available) > 0) {
      overview.available = apiSnap.available
      overview.availableUsdt = apiSnap.availableUsdt
    }
    if (Number(overview.locked) === 0 && Number(apiSnap.locked) > 0) {
      overview.locked = apiSnap.locked
      overview.lockedUsdt = apiSnap.lockedUsdt
    }
    if (Number(overview.released) === 0 && Number(apiSnap.released) > 0) {
      overview.released = apiSnap.released
    }
  }
  return { overview, transferAvailable }
}

/** 从 staking_wallet 表读取指定币种质押钱包余额（/uc/staking/wallet） */
export async function loadStakingWalletSnapshot(coinUnit: string = STAKING_COIN_UNIT): Promise<StakingAccountSnapshot> {
  try {
    const w = await fetchStakingWalletBalance(coinUnit)
    return parseStakingWalletRow(w)
  } catch {
    return {
      available: '0',
      locked: '0',
      released: '0',
      availableUsdt: '0',
      lockedUsdt: '0',
    }
  }
}

export async function loadStakingTransferBalances(coinUnit: string = STAKING_COIN_UNIT): Promise<{
  staking: StakingAccountSnapshot
  fundIbit: string
}> {
  const [staking, fundIbit] = await Promise.all([
    loadStakingWalletSnapshot(coinUnit),
    loadFundCoinBalance(coinUnit),
  ])
  return { staking, fundIbit }
}

/** 资金账户 ↔ 质押钱包（iBit） */
export function involvesStakingFundBridge(from: string, to: string): boolean {
  return (from === 'SPOT' && to === 'STAKING') || (from === 'STAKING' && to === 'SPOT')
}
