import 'dart:convert';
import 'dart:math';
import 'package:flutter/foundation.dart';
import '../network/api_client.dart';
import '../storage/local_storage.dart';
import '../storage/storage_keys.dart';

/// 应用资源数据模型
class AppAssetData {
  final String id;
  final String type; // 'SPLASH' | 'GUIDE'
  final int sortOrder;
  final String imageUrl;
  final String? title;
  final String? subtitle;

  const AppAssetData({
    required this.id,
    required this.type,
    required this.sortOrder,
    required this.imageUrl,
    this.title,
    this.subtitle,
  });

  factory AppAssetData.fromJson(Map<String, dynamic> json) {
    return AppAssetData(
      id: json['id'] as String,
      type: json['type'] as String,
      sortOrder: json['sortOrder'] as int,
      imageUrl: json['imageUrl'] as String,
      title: json['title'] as String?,
      subtitle: json['subtitle'] as String?,
    );
  }

  Map<String, dynamic> toJson() => {
        'id': id,
        'type': type,
        'sortOrder': sortOrder,
        'imageUrl': imageUrl,
        'title': title,
        'subtitle': subtitle,
      };
}

/// 应用资源配置（包含开屏图和引导图）
class AppAssetConfig {
  final List<AppAssetData> splashImages;
  final List<AppAssetData> guideImages;

  const AppAssetConfig({
    required this.splashImages,
    required this.guideImages,
  });

  /// 从 API 响应列表解析
  factory AppAssetConfig.fromList(List<dynamic> list) {
    final assets = list.map((e) => AppAssetData.fromJson(e as Map<String, dynamic>)).toList();
    return AppAssetConfig(
      splashImages: assets.where((a) => a.type == 'SPLASH').toList()
        ..sort((a, b) => a.sortOrder.compareTo(b.sortOrder)),
      guideImages: assets.where((a) => a.type == 'GUIDE').toList()
        ..sort((a, b) => a.sortOrder.compareTo(b.sortOrder)),
    );
  }

  bool get hasSplashImages => splashImages.isNotEmpty;
  bool get hasGuideImages => guideImages.isNotEmpty;

  /// 随机获取一个开屏图 URL
  String? get randomSplashImageUrl {
    if (splashImages.isEmpty) return null;
    return splashImages[Random().nextInt(splashImages.length)].imageUrl;
  }

  /// 序列化为 JSON 字符串
  String toJsonString() {
    final list = [...splashImages, ...guideImages].map((e) => e.toJson()).toList();
    return jsonEncode(list);
  }

  /// 从 JSON 字符串反序列化
  static AppAssetConfig? fromJsonString(String? jsonStr) {
    if (jsonStr == null || jsonStr.isEmpty) return null;
    try {
      final list = jsonDecode(jsonStr) as List<dynamic>;
      return AppAssetConfig.fromList(list);
    } catch (e) {
      debugPrint('[AppAssetService] 反序列化缓存失败: $e');
      return null;
    }
  }
}

/// 应用资源服务
///
/// 负责从后端获取开屏图和引导图配置。
/// 策略：
///   1. 优先使用 SharedPreferences 中的持久化缓存
///   2. 后台静默刷新，成功后更新缓存
///   3. 缓存为空时调用方回退到本地 asset
///   4. 图片变更在用户下次启动应用时生效
class AppAssetService {
  final ApiClient _apiClient;
  final LocalStorage _localStorage;

  /// 内存缓存
  AppAssetConfig? _memoryCache;

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

  /// 上次网络请求时间
  DateTime? _lastFetchTime;

  AppAssetService({
    required ApiClient apiClient,
    required LocalStorage localStorage,
  })  : _apiClient = apiClient,
        _localStorage = localStorage;

  /// 获取应用资源配置
  ///
  /// 返回顺序：内存缓存 → 持久化缓存 → null（调用方回退到本地 asset）
  /// 同时在后台静默刷新数据。
  Future<AppAssetConfig?> getConfig({bool forceRefresh = false}) async {
    // 1. 检查内存缓存
    if (!forceRefresh && _memoryCache != null && _lastFetchTime != null) {
      final cacheAge = DateTime.now().difference(_lastFetchTime!);
      if (cacheAge < _cacheExpiration) {
        return _memoryCache;
      }
    }

    // 2. 从 SharedPreferences 加载
    if (_memoryCache == null) {
      try {
        final cachedJson = _localStorage.getString(StorageKeys.cachedAppAssets);
        final cached = AppAssetConfig.fromJsonString(cachedJson);
        if (cached != null) {
          _memoryCache = cached;
          debugPrint('[AppAssetService] 从持久化缓存加载: '
              '${cached.splashImages.length} splash, '
              '${cached.guideImages.length} guide');
        }
      } catch (e) {
        debugPrint('[AppAssetService] 读取持久化缓存失败: $e');
      }
    }

    // 3. 后台静默刷新
    _refreshInBackground();

    return _memoryCache;
  }

  /// 后台静默刷新
  void _refreshInBackground() {
    _fetchFromApi().then((config) {
      if (config != null) {
        _memoryCache = config;
        _lastFetchTime = DateTime.now();
        // 持久化
        _localStorage.setString(
          StorageKeys.cachedAppAssets,
          config.toJsonString(),
        );
        debugPrint('[AppAssetService] 后台刷新成功: '
            '${config.splashImages.length} splash, '
            '${config.guideImages.length} guide');
      }
    }).catchError((e) {
      debugPrint('[AppAssetService] 后台刷新失败: $e');
    });
  }

  /// 从 API 获取数据
  Future<AppAssetConfig?> _fetchFromApi() async {
    try {
      final response = await _apiClient.get(
        '/app-assets',
      );
      if (response.data is List) {
        return AppAssetConfig.fromList(response.data as List);
      }
      // 如果返回的是 Map 且有 data 字段
      if (response.data is Map && response.data['data'] is List) {
        return AppAssetConfig.fromList(response.data['data'] as List);
      }
      return null;
    } catch (e) {
      debugPrint('[AppAssetService] API 请求失败: $e');
      return null;
    }
  }
}
