import 'package:flutter/material.dart';
import '../data/models/coin.dart';
import '../data/services/market_service.dart';

/// 行情状态管理
class MarketProvider extends ChangeNotifier {
  final MarketService _marketService;

  List<Coin> _allCoins = [];
  List<Coin> _filteredCoins = [];
  String _activeTab = 'all';
  String _searchKeyword = '';
  bool _isLoading = false;
  String? _error;

  MarketProvider(this._marketService);

  // Getters
  List<Coin> get coins => _filteredCoins;
  List<Coin> get allCoins => _allCoins;
  bool get isLoading => _isLoading;
  String? get error => _error;
  String get activeTab => _activeTab;
  String get searchKeyword => _searchKeyword;

  /// 加载币种列表
  Future<void> loadCoins() async {
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      final response = await _marketService.getCoinList();

      if (response.success) {
        _allCoins = response.data ?? [];
        _filterCoins();
      } else {
        _error = response.message;
      }
    } catch (e) {
      _error = '加载失败: $e';
    }

    _isLoading = false;
    notifyListeners();
  }

  /// 设置分类标签
  void setTab(String tab) {
    _activeTab = tab;
    _filterCoins();
    notifyListeners();
  }

  /// 搜索
  void search(String keyword) {
    _searchKeyword = keyword;
    _filterCoins();
    notifyListeners();
  }

  /// 清除搜索
  void clearSearch() {
    _searchKeyword = '';
    _filterCoins();
    notifyListeners();
  }

  /// 筛选币种
  void _filterCoins() {
    List<Coin> result = List.from(_allCoins);

    // 按分类筛选
    if (_activeTab == 'realtime') {
      result = result.where((c) => c.isRealtime).toList();
    } else if (_activeTab == 'hot') {
      result = result.take(6).toList();
    }

    // 按关键词筛选
    if (_searchKeyword.isNotEmpty) {
      final kw = _searchKeyword.toLowerCase();
      result = result.where((c) =>
          c.code.toLowerCase().contains(kw) ||
          c.name.toLowerCase().contains(kw)).toList();
    }

    _filteredCoins = result;
  }

  /// 根据代码获取币种
  Coin? getCoinByCode(String code) {
    try {
      return _allCoins.firstWhere((c) => c.code == code);
    } catch (_) {
      return null;
    }
  }

  /// 刷新
  Future<void> refresh() async {
    await loadCoins();
  }
}
