import 'package:dio/dio.dart';

import '../models/home/activity_banner.dart';
import '../models/home/app_header_item.dart';
import '../models/home/market_ticker.dart';

/// 行情 API 服务
class MarketService {
  const MarketService(this._dio);

  final Dio _dio;

  /// 获取合约币对列表（/swap/coin/enabled-list）
  /// 返回交易对静态信息（symbol, icon, isHot 等），价格由 WebSocket 推送
  Future<List<MarketTicker>> getEnabledCoins() async {
    final response = await _dio.get<Map<String, dynamic>>('swap/coin/enabled-list');
    final raw = response.data?['data'];

    final List<dynamic> list;
    if (raw is List) {
      list = raw;
    } else if (raw is Map && raw['data'] is List) {
      list = raw['data'] as List;
    } else {
      list = [];
    }

    return list
        .whereType<Map<String, dynamic>>()
        .map((e) => MarketTicker.fromJson(e))
        .toList();
  }

  /// 获取涨幅榜 (/market-new/rank/rise)
  Future<List<MarketTicker>> getRiseRank() async {
    return _fetchRank('market-new/rank/rise');
  }

  /// 获取跌幅榜 (/market-new/rank/fall)
  Future<List<MarketTicker>> getFallRank() async {
    return _fetchRank('market-new/rank/fall');
  }

  /// 通用排行榜请求
  Future<List<MarketTicker>> _fetchRank(String path) async {
    final response = await _dio.get<Map<String, dynamic>>(path);
    final raw = response.data?['data'];
    if (raw is! List) return [];

    return raw.whereType<Map<String, dynamic>>().map((json) {
      // symbol: "BTCUSDT", closePrice: "92328.30", changePercent: 1.60, volume: "123000"
      final symbol = json['symbol'] as String? ?? '';
      final base = symbol.replaceAll('USDT', '');
      return MarketTicker(
        symbol: symbol,
        baseAsset: base,
        lastPrice: double.tryParse(json['closePrice']?.toString() ?? '') ?? 0,
        change24h: (json['changePercent'] as num?)?.toDouble() ?? 0,
        volume24h: double.tryParse(json['volume']?.toString() ?? '') ?? 0,
        isFutures: true,
      );
    }).toList();
  }

  /// 获取首页 Banner 列表
  Future<List<ActivityBanner>> getBanners() async {
    final response = await _dio.get<Map<String, dynamic>>(
      'contract/app-banner/active-list',
    );
    final list = response.data?['data'] as List<dynamic>? ?? [];
    return list
        .map((e) => ActivityBanner.fromJson(e as Map<String, dynamic>))
        .toList();
  }

  /// 获取首页 Header 列表（视频/图片）
  Future<List<AppHeaderItem>> getAppHeaders() async {
    final response = await _dio.get<Map<String, dynamic>>(
      'contract/app-header/active-list',
    );
    final list = response.data?['data'] as List<dynamic>? ?? [];
    return list
        .map((e) => AppHeaderItem.fromJson(e as Map<String, dynamic>))
        .toList();
  }
}
