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

/// 热度展示方式
enum HeatDisplayMode {
  /// 显示具体认种数量
  count,
  /// 仅显示热度等级（高/中/低）
  level,
}

/// 前端展示设置
class DisplaySettings {
  /// 是否允许未认种用户查看各省认种热度
  final bool allowNonAdopterViewHeat;

  /// 热度展示方式
  final HeatDisplayMode heatDisplayMode;

  DisplaySettings({
    required this.allowNonAdopterViewHeat,
    required this.heatDisplayMode,
  });

  factory DisplaySettings.fromJson(Map<String, dynamic> json) {
    return DisplaySettings(
      allowNonAdopterViewHeat: json['allowNonAdopterViewHeat'] ?? false,
      heatDisplayMode: _parseHeatDisplayMode(json['heatDisplayMode']),
    );
  }

  static HeatDisplayMode _parseHeatDisplayMode(String? mode) {
    switch (mode) {
      case 'level':
        return HeatDisplayMode.level;
      case 'count':
      default:
        return HeatDisplayMode.count;
    }
  }

  /// 默认设置
  factory DisplaySettings.defaultSettings() {
    return DisplaySettings(
      allowNonAdopterViewHeat: false,
      heatDisplayMode: HeatDisplayMode.count,
    );
  }
}

/// 系统配置服务
class SystemConfigService {
  final ApiClient _apiClient;

  /// 缓存的展示设置
  DisplaySettings? _cachedDisplaySettings;

  /// 上次获取设置的时间
  DateTime? _lastFetchTime;

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

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

  /// 获取前端展示设置
  ///
  /// [forceRefresh] 强制刷新，不使用缓存
  Future<DisplaySettings> getDisplaySettings({bool forceRefresh = false}) async {
    // 检查缓存是否有效
    if (!forceRefresh && _cachedDisplaySettings != null && _lastFetchTime != null) {
      final cacheAge = DateTime.now().difference(_lastFetchTime!);
      if (cacheAge < _cacheExpiration) {
        return _cachedDisplaySettings!;
      }
    }

    try {
      final response = await _apiClient.get(
        '/system-config/display/settings',
      );

      _cachedDisplaySettings = DisplaySettings.fromJson(response.data);
      _lastFetchTime = DateTime.now();

      debugPrint('[SystemConfigService] 获取展示设置成功: allowNonAdopterViewHeat=${_cachedDisplaySettings!.allowNonAdopterViewHeat}, heatDisplayMode=${_cachedDisplaySettings!.heatDisplayMode}');

      return _cachedDisplaySettings!;
    } catch (e) {
      debugPrint('[SystemConfigService] 获取展示设置失败: $e');

      // 如果有缓存则返回缓存，否则返回默认设置
      return _cachedDisplaySettings ?? DisplaySettings.defaultSettings();
    }
  }

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

  /// 检查用户是否可以查看省份热度
  ///
  /// [hasAdopted] 用户是否已认种
  Future<bool> canViewProvinceHeat({required bool hasAdopted}) async {
    if (hasAdopted) {
      // 已认种用户始终可以查看
      return true;
    }

    final settings = await getDisplaySettings();
    return settings.allowNonAdopterViewHeat;
  }

  /// 获取当前的热度展示方式
  Future<HeatDisplayMode> getHeatDisplayMode() async {
    final settings = await getDisplaySettings();
    return settings.heatDisplayMode;
  }
}
