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

/// 龙虎榜开关状态
class LeaderboardStatus {
  /// 日榜是否开启
  final bool dailyEnabled;

  /// 周榜是否开启
  final bool weeklyEnabled;

  /// 月榜是否开启
  final bool monthlyEnabled;

  LeaderboardStatus({
    required this.dailyEnabled,
    required this.weeklyEnabled,
    required this.monthlyEnabled,
  });

  factory LeaderboardStatus.fromJson(Map<String, dynamic> json) {
    return LeaderboardStatus(
      dailyEnabled: json['dailyEnabled'] ?? false,
      weeklyEnabled: json['weeklyEnabled'] ?? false,
      monthlyEnabled: json['monthlyEnabled'] ?? false,
    );
  }

  /// 检查是否有任何榜单开启
  bool get hasAnyEnabled => dailyEnabled || weeklyEnabled || monthlyEnabled;

  /// 默认状态（全部关闭）
  factory LeaderboardStatus.allDisabled() {
    return LeaderboardStatus(
      dailyEnabled: false,
      weeklyEnabled: false,
      monthlyEnabled: false,
    );
  }
}

/// 龙虎榜服务
class LeaderboardService {
  final ApiClient _apiClient;

  /// 缓存的榜单状态
  LeaderboardStatus? _cachedStatus;

  /// 上次获取状态的时间
  DateTime? _lastFetchTime;

  /// 缓存有效期（5分钟）
  static const Duration _cacheExpiration = Duration(minutes: 5);

  LeaderboardService({required ApiClient apiClient}) : _apiClient = apiClient;

  /// 获取龙虎榜开关状态
  ///
  /// [forceRefresh] 强制刷新，不使用缓存
  Future<LeaderboardStatus> getStatus({bool forceRefresh = false}) async {
    // 检查缓存是否有效
    if (!forceRefresh && _cachedStatus != null && _lastFetchTime != null) {
      final cacheAge = DateTime.now().difference(_lastFetchTime!);
      if (cacheAge < _cacheExpiration) {
        return _cachedStatus!;
      }
    }

    try {
      final response = await _apiClient.get(
        '/leaderboard/status',
      );

      if (response.data != null && response.data['data'] != null) {
        _cachedStatus = LeaderboardStatus.fromJson(response.data['data']);
      } else {
        _cachedStatus = LeaderboardStatus.allDisabled();
      }
      _lastFetchTime = DateTime.now();

      debugPrint(
          '[LeaderboardService] 获取榜单状态成功: daily=${_cachedStatus!.dailyEnabled}, weekly=${_cachedStatus!.weeklyEnabled}, monthly=${_cachedStatus!.monthlyEnabled}');

      return _cachedStatus!;
    } catch (e) {
      debugPrint('[LeaderboardService] 获取榜单状态失败: $e');

      // 如果有缓存则返回缓存，否则返回全部关闭
      return _cachedStatus ?? LeaderboardStatus.allDisabled();
    }
  }

  /// 清除缓存
  void clearCache() {
    _cachedStatus = null;
    _lastFetchTime = null;
  }
}
