import 'package:dio/dio.dart';

import '../models/asset/recharge_order.dart';

/// 链上充值订单 API（与 Web `stores/deposit.ts` 路径一致）
class RechargeService {
  const RechargeService(this._dio);

  final Dio _dio;

  Future<List<RechargeParentCoin>> getRechargeParents() async {
    final response = await _dio.get<Map<String, dynamic>>(
      'uc/coin-network/recharge-parents',
    );
    final data = response.data?['data'];
    if (data is List) {
      return data
          .whereType<Map<String, dynamic>>()
          .map(RechargeParentCoin.fromJson)
          .toList()
        ..sort((a, b) => a.sort.compareTo(b.sort));
    }
    return [];
  }

  Future<List<RechargeFlatNetworkOption>> getChildrenWithNetwork({
    required String coinName,
  }) async {
    final response = await _dio.get<Map<String, dynamic>>(
      'uc/coin-network/children-with-network',
      queryParameters: {'coinName': coinName},
    );
    final data = response.data?['data'];
    if (data is! List) {
      return [];
    }
    final out = <_FlatNetSort>[];
    for (final raw in data.whereType<Map<String, dynamic>>()) {
      final coin = raw['coin'];
      if (coin is! Map<String, dynamic>) {
        continue;
      }
      final coinNameRaw = coin['name']?.toString() ?? '';
      final coinNameCnRaw = coin['nameCn']?.toString() ?? '';
      final nets = raw['networkConfigs'];
      if (nets is! List) {
        continue;
      }
      for (final n in nets.whereType<Map<String, dynamic>>()) {
        final network = n['network'];
        final protocol = network is Map<String, dynamic>
            ? network['protocol']?.toString() ?? ''
            : '';
        final netName = network is Map<String, dynamic>
            ? network['name']?.toString() ?? ''
            : '';
        final cfgId =
            int.tryParse(n['id']?.toString() ?? '') ?? 0;
        final sort = int.tryParse(n['sort']?.toString() ?? '') ?? 0;
        out.add(
          _FlatNetSort(
            sort: sort,
            option: RechargeFlatNetworkOption(
              coinName: coinNameRaw,
              coinNameCn: coinNameCnRaw,
              networkConfigId: cfgId,
              networkName: netName,
              protocol: protocol,
              contractAddress: n['contractAddress']?.toString() ?? '',
              rechargeAddress: n['rechargeAddress']?.toString() ?? '',
            ),
          ),
        );
      }
    }
    out.sort((a, b) => a.sort.compareTo(b.sort));
    return out.map((e) => e.option).toList();
  }

  Future<RechargeOrderDetail> createRechargeOrder({
    required String coinName,
    required int networkConfigId,
    required String amount,
  }) async {
    final response = await _dio.post<Map<String, dynamic>>(
      'uc/recharge/create',
      data: {
        'coinName': coinName,
        'networkConfigId': networkConfigId.toString(),
        'amount': amount.trim(),
      },
      options: Options(contentType: Headers.formUrlEncodedContentType),
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      return RechargeOrderDetail.fromJson(data);
    }
    throw StateError('create recharge: invalid response');
  }

  Future<RechargeOrderDetail> submitTxHash({
    required String orderNo,
    required String txHash,
  }) async {
    final response = await _dio.post<Map<String, dynamic>>(
      'uc/recharge/submit-hash',
      data: {
        'orderNo': orderNo,
        'txHash': txHash.trim(),
      },
      options: Options(contentType: Headers.formUrlEncodedContentType),
    );
    final data = response.data?['data'];
    if (data is Map<String, dynamic>) {
      return RechargeOrderDetail.fromJson(data);
    }
    throw StateError('submit-hash: invalid response');
  }
}

class _FlatNetSort {
  _FlatNetSort({required this.sort, required this.option});

  final int sort;
  final RechargeFlatNetworkOption option;
}
