import 'package:flutter/foundation.dart';
import '../network/api_client.dart';
import '../storage/secure_storage.dart';
import '../storage/storage_keys.dart';

/// 充值地址响应
class DepositAddressResponse {
  final String? kavaAddress;
  final String? bscAddress;
  final String? dstAddress;
  final bool isValid;
  final String? message;

  DepositAddressResponse({
    this.kavaAddress,
    this.bscAddress,
    this.dstAddress,
    required this.isValid,
    this.message,
  });

  factory DepositAddressResponse.fromJson(Map<String, dynamic> json) {
    return DepositAddressResponse(
      kavaAddress: json['kavaAddress'],
      bscAddress: json['bscAddress'],
      dstAddress: json['dstAddress'],
      isValid: json['isValid'] ?? false,
      message: json['message'],
    );
  }
}

/// USDT 余额信息
class UsdtBalance {
  final String chainType;
  final String address;
  final String balance;
  final String rawBalance;
  final int decimals;

  UsdtBalance({
    required this.chainType,
    required this.address,
    required this.balance,
    required this.rawBalance,
    required this.decimals,
  });

  factory UsdtBalance.fromJson(Map<String, dynamic> json) {
    return UsdtBalance(
      chainType: json['chainType'] ?? '',
      address: json['address'] ?? '',
      balance: json['balance'] ?? '0',
      rawBalance: json['rawBalance'] ?? '0',
      decimals: json['decimals'] ?? 6,
    );
  }
}

/// 余额响应
class BalanceResponse {
  final UsdtBalance? kava;
  final UsdtBalance? bsc;

  BalanceResponse({
    this.kava,
    this.bsc,
  });

  factory BalanceResponse.fromJson(Map<String, dynamic> json) {
    return BalanceResponse(
      kava: json['kava'] != null ? UsdtBalance.fromJson(json['kava']) : null,
      bsc: json['bsc'] != null ? UsdtBalance.fromJson(json['bsc']) : null,
    );
  }
}

/// 充值服务
///
/// 提供充值地址获取和余额查询功能
class DepositService {
  final ApiClient _apiClient;
  final SecureStorage _secureStorage;

  DepositService({
    required ApiClient apiClient,
    required SecureStorage secureStorage,
  })  : _apiClient = apiClient,
        _secureStorage = secureStorage;

  /// 获取充值地址
  ///
  /// 始终从服务器获取，确保返回当前登录用户的正确地址
  /// 不使用本地缓存，避免切换账号后显示错误的地址
  /// 返回用户的 KAVA 和 BSC 充值地址
  Future<DepositAddressResponse> getDepositAddresses() async {
    try {
      debugPrint('获取充值地址...');

      // 始终从服务器获取，确保是当前用户的地址
      debugPrint('从服务器获取钱包地址...');
      final response = await _apiClient.get('/user/wallet');

      if (response.statusCode == 200) {
        final responseData = response.data as Map<String, dynamic>;
        final data = responseData['data'] as Map<String, dynamic>?;

        if (data != null && data['status'] == 'ready') {
          final addresses = data['walletAddresses'] as Map<String, dynamic>?;
          if (addresses != null) {
            final kava = addresses['kava'] as String?;
            final bsc = addresses['bsc'] as String?;
            final dst = addresses['dst'] as String?;

            debugPrint('从服务器获取充值地址成功: kava=$kava, bsc=$bsc, dst=$dst');

            // 保存到本地存储
            if (kava != null && kava.isNotEmpty) {
              await _secureStorage.write(key: StorageKeys.walletAddressKava, value: kava);
            }
            if (bsc != null && bsc.isNotEmpty) {
              await _secureStorage.write(key: StorageKeys.walletAddressBsc, value: bsc);
            }
            if (dst != null && dst.isNotEmpty) {
              await _secureStorage.write(key: StorageKeys.walletAddressDst, value: dst);
            }

            return DepositAddressResponse(
              kavaAddress: kava,
              bscAddress: bsc,
              dstAddress: dst,
              isValid: kava != null && bsc != null && dst != null,
              message: (kava == null || bsc == null || dst == null) ? '部分地址未生成' : null,
            );
          }
        } else if (data != null && data['status'] == 'generating') {
          return DepositAddressResponse(
            isValid: false,
            message: '钱包生成中，请稍后重试',
          );
        }
      }

      return DepositAddressResponse(
        isValid: false,
        message: '获取充值地址失败',
      );
    } catch (e) {
      debugPrint('获取充值地址失败: $e');
      return DepositAddressResponse(
        isValid: false,
        message: '获取充值地址失败: $e',
      );
    }
  }

  /// 查询 USDT 余额
  ///
  /// 实时查询 KAVA 和 BSC 链上的 USDT 余额
  Future<BalanceResponse> getUsdtBalances() async {
    try {
      debugPrint('查询 USDT 余额...');
      final response = await _apiClient.get('/deposit/balances');

      if (response.statusCode == 200) {
        final data = response.data as Map<String, dynamic>;
        debugPrint('USDT 余额查询成功');
        return BalanceResponse.fromJson(data);
      }

      throw Exception('查询余额失败');
    } catch (e) {
      debugPrint('查询 USDT 余额失败: $e');
      rethrow;
    }
  }
}
