import '../../data/models/asset/today_pnl.dart';
import '../../data/models/finance/staking_wallet_balance.dart';

/// 解析现货各币种可用余额（对齐 Web `parseSpotAvailableMap`）。
Map<String, String> parseSpotAvailableMap(Map<String, dynamic> spotData) {
  final map = <String, String>{};
  final list = spotData['assetList'];
  if (list is! List) {
    return map;
  }
  for (final item in list) {
    if (item is! Map<String, dynamic>) {
      continue;
    }
    final coin = '${item['symbol'] ?? item['coinId'] ?? item['coin'] ?? ''}'
        .toUpperCase()
        .trim();
    if (coin.isEmpty) {
      continue;
    }
    final avail = item['available'] ?? item['balance'];
    map[coin] = '${avail ?? '0'}';
  }
  return map;
}

/// 现货币种开放列表（对齐 Web `parseOpenCoinSymbols`）。
List<String> parseOpenCoinSymbols(List<Map<String, dynamic>> coinsRaw) {
  final set = <String>{};
  for (final item in coinsRaw) {
    final sym =
        '${item['symbol'] ?? item['coinSymbol'] ?? ''}'.toUpperCase().trim();
    if (sym.isNotEmpty) {
      set.add(sym);
    }
  }
  final list = set.toList()
    ..sort((a, b) {
      if (a == 'USDT') {
        return -1;
      }
      if (b == 'USDT') {
        return 1;
      }
      return a.compareTo(b);
    });
  if (list.isEmpty) {
    return const ['USDT'];
  }
  return list;
}

/// 资金账户各币种可用余额（对齐 Web `parseFundWalletBalances`）。
Map<String, String> parseFundWalletBalances(dynamic raw) {
  final map = <String, String>{};
  final arr = raw is List
      ? raw
      : raw is Map<String, dynamic> && raw['data'] is List
          ? raw['data'] as List
          : null;
  if (arr == null) {
    return map;
  }
  for (final item in arr) {
    if (item is! Map<String, dynamic>) {
      continue;
    }
    final coin = item['coin'];
    final unit = '${item['coinUnit'] ?? (coin is Map ? coin['unit'] ?? coin['name'] : null) ?? item['unit'] ?? ''}'
        .toUpperCase()
        .trim();
    if (unit.isEmpty) {
      continue;
    }
    final bal = item['balance'] ?? item['available'] ?? item['useBalance'];
    map[unit] = '${bal ?? '0'}';
  }
  return map;
}

AccountInfo? pickStakingAccount(List<AccountInfo> list) {
  for (final row in list) {
    final name = row.name.trim();
    if (name.contains('质押') || name.toLowerCase().contains('staking')) {
      return row;
    }
  }
  return null;
}

String stakingOverviewLockedFromAccounts(List<AccountInfo> list) {
  final row = pickStakingAccount(list);
  if (row == null) {
    return '0';
  }
  return row.frozenBalance.toString();
}

String stakingOverviewAvailableFromAccounts(List<AccountInfo> list) {
  final row = pickStakingAccount(list);
  if (row == null) {
    return '0';
  }
  return row.balance.toString();
}

/// 总览锁仓余额合并 wallet-new 与 staking/wallet（对齐 Web applyStakingOverviewBalances）
({String available, String locked}) mergeStakingOverviewBalances({
  required String walletAvailable,
  required String walletLocked,
  StakingWalletBalance? apiWallet,
}) {
  var available = walletAvailable;
  var locked = walletLocked;
  if (apiWallet == null) {
    return (available: available, locked: locked);
  }
  final apiAvailable = apiWallet.availableBalance;
  final apiLocked = apiWallet.lockedBalance;
  if ((double.tryParse(available) ?? 0) <= 0 &&
      (double.tryParse(apiAvailable) ?? 0) > 0) {
    available = apiAvailable;
  }
  if ((double.tryParse(locked) ?? 0) <= 0 &&
      (double.tryParse(apiLocked) ?? 0) > 0) {
    locked = apiLocked;
  }
  return (available: available, locked: locked);
}
