import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../core/network/dio_client.dart';
import '../data/models/home/market_ticker.dart';
import '../data/services/market_service.dart';

/// 全局币对缓存 — 缓存 /swap/coin/enabled-list 返回的所有交易对信息
/// 包含 icon、isHot 等静态字段，供首页、行情页等多处复用
class CoinCacheNotifier extends Notifier<Map<String, MarketTicker>> {
  @override
  Map<String, MarketTicker> build() {
    Future.microtask(_load);
    return {};
  }

  Future<void> _load() async {
    try {
      final dio = ref.read(dioClientProvider);
      final coins = await MarketService(dio).getEnabledCoins();
      state = {for (final c in coins) c.symbol: c};
      // 预缓存所有币种图标，切换到行情页时直接命中缓存
      final cacheManager = DefaultCacheManager();
      for (final c in coins) {
        if (c.icon.isNotEmpty) {
          cacheManager.downloadFile(c.icon).ignore();
        }
      }
    } catch (_) {}
  }

  /// 刷新缓存
  Future<void> refresh() => _load();

  /// 根据 symbol 查找币对信息（icon 等）
  MarketTicker? getBySymbol(String symbol) => state[symbol];

  /// 将排行榜数据与缓存的币对信息合并（补充 icon、isHot）
  List<MarketTicker> mergeWithRank(List<MarketTicker> rankTickers) {
    return rankTickers.map((t) {
      final cached = state[t.symbol];
      if (cached == null) return t;
      return t.copyWith(
        icon: cached.icon,
        isHot: cached.isHot,
        baseAsset: cached.baseAsset.isNotEmpty ? cached.baseAsset : t.baseAsset,
        pricePrecision: cached.pricePrecision,
      );
    }).toList();
  }
}

final coinCacheProvider =
    NotifierProvider<CoinCacheNotifier, Map<String, MarketTicker>>(
  CoinCacheNotifier.new,
);
