import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';

class DataPersistence {
  static SharedPreferences? _prefs;
  static bool _isInitialized = false;
  static Completer<void>? _initializationCompleter;

  // 初始化 SharedPreferences
  static Future<void> initialize() async {
    if (_isInitialized) return;

    if (_initializationCompleter != null) {
      return _initializationCompleter!.future;
    }

    _initializationCompleter = Completer<void>();

    try {
      _prefs = await SharedPreferences.getInstance();
      _isInitialized = true;
      _initializationCompleter!.complete();
      debugPrint('SharedPreferences initialized successfully');
    } catch (e) {
      _initializationCompleter!.completeError(e);
      _initializationCompleter = null;
      debugPrint('SharedPreferences initialization failed: $e');
      rethrow;
    }
  }

  // 检查是否已初始化
  static void _checkInitialized() {
    if (!_isInitialized || _prefs == null) {
      throw Exception(
        "SharedPreferences not initialized! Call DataPersistence.initialize() first.",
      );
    }
  }

  // 存储字符串
  static Future<bool> setString(String key, String value) async {
    _checkInitialized();
    return await _prefs!.setString(key, value);
  }

  // 读取字符串
  static String getString(String key, {String defaultValue = ''}) {
    if (!_isInitialized) return defaultValue;
    return _prefs!.getString(key) ?? defaultValue;
  }

  // 存储整数
  static Future<bool> setInt(String key, int value) async {
    _checkInitialized();
    return await _prefs!.setInt(key, value);
  }

  // 读取整数
  static int getInt(String key, {int defaultValue = 0}) {
    if (!_isInitialized) return defaultValue;
    return _prefs!.getInt(key) ?? defaultValue;
  }

  // 存储布尔值
  static Future<bool> setBool(String key, bool value) async {
    _checkInitialized();
    return await _prefs!.setBool(key, value);
  }

  // 读取布尔值
  static bool getBool(String key, {bool defaultValue = false}) {
    if (!_isInitialized) return defaultValue;
    return _prefs!.getBool(key) ?? defaultValue;
  }

  // 存储双精度浮点数
  static Future<bool> setDouble(String key, double value) async {
    _checkInitialized();
    return await _prefs!.setDouble(key, value);
  }

  // 读取双精度浮点数
  static double getDouble(String key, {double defaultValue = 0.0}) {
    if (!_isInitialized) return defaultValue;
    return _prefs!.getDouble(key) ?? defaultValue;
  }

  // 删除指定键
  static Future<bool> remove(String key) async {
    if (!_isInitialized) return false;
    return await _prefs!.remove(key);
  }

  // 批量删除（通过键前缀）
  static Future<void> removeByPrefix(String prefix) async {
    if (!_isInitialized) return;

    final keys = _prefs!.getKeys().where((key) => key.startsWith(prefix));
    for (final key in keys) {
      await _prefs!.remove(key);
    }
  }

  // 清空所有数据
  static Future<bool> clearAll() async {
    if (!_isInitialized) return false;
    return await _prefs!.clear();
  }

  // 检查键是否存在
  static bool containsKey(String key) {
    if (!_isInitialized) return false;
    return _prefs!.containsKey(key);
  }

  // 获取所有键
  static Set<String> getKeys() {
    if (!_isInitialized) return {};
    return _prefs!.getKeys();
  }

  // 业务方法 - 与之前保持相同的API
  static String getToken() {
    return getString("token");
  }

  static Future<bool> setToken(String token) async {
    return await setString("token", token);
  }

  ///获取当前用户
  static String getCurrentUser() {
    return getString("currentUser");
  }

  ///保存当前用户
  static Future<bool> setCurrentUser(String userJson) async {
    return await setString("currentUser", userJson);
  }

  ///保存搜索历史记录
  static Future<bool> setSearchHistroy(String userId, String userJson) async {
    return await setString("${userId}-currentUser", userJson);
  }

  ///获取搜索历史记录
  static String getSearchHistroy(String userId) {
    return getString("${userId}-currentUser");
  }

  ///保存当前语言
  static Future<bool> setLang(String value) async {
    return await setString("lang", value);
  }

  ///获取当前语言
  static String getLang() {
    return getString("lang");
  }

  static Future<bool> setUniqueId(String value) async {
    return await setString("device_unique_id", value);
  }

  static String getUniqueId() {
    return getString("device_unique_id");
  }

  static Future<bool> setLastTimeRoomId(String id) async {
    return await setString("last_time_room_id", id);
  }

  static String getLastTimeRoomId() {
    return getString("last_time_room_id");
  }

  static Future<bool> setPlayGiftMusic(bool muteMusic) async {
    return await setBool("play_gift_music", muteMusic);
  }

  static bool getPlayGiftMusic() {
    return getBool("play_gift_music");
  }

  ///获取用户已经添加的房间音乐
  static String getUserRoomMusic() {
    final currentUser = AccountStorage().getCurrentUser()?.userProfile?.account;
    if (currentUser == null) return "";
    return getString("room_music$currentUser");
  }

  static Future<bool> setUserRoomMusic(String musicJson) async {
    final currentUser = AccountStorage().getCurrentUser()?.userProfile?.account;
    if (currentUser == null) return false;
    return await setString("room_music$currentUser", musicJson);
  }

  // 等待初始化完成
  static Future<void> get initializationDone {
    if (_isInitialized) return Future.value();
    return _initializationCompleter?.future ?? Future.value();
  }

  // 重置初始化状态（用于测试）
  static void reset() {
    _isInitialized = false;
    _prefs = null;
    _initializationCompleter = null;
  }

  ///发送动态的草稿图片
  static List<String> getDraftDynamicPhoto() {
    String st = getString(
      "draft_dynamic_photo${AccountStorage().getCurrentUser()?.userProfile?.account}",
    );
    List<String> photos = [];
    if (st.isNotEmpty) {
      photos = (jsonDecode(st) as List).map((e) => e as String).toList();
    }
    return photos;
  }

  static void setDraftDynamicPhoto(List<String> images) {
    setString(
      "draft_dynamic_photo${AccountStorage().getCurrentUser()?.userProfile?.account}",
      jsonEncode(images),
    );
  }

  ///发送动态的草稿文本
  static String getDraftDynamicText() {
    return getString(
      "draft_dynamic_text${AccountStorage().getCurrentUser()?.userProfile?.account}",
    );
  }

  static void setDraftDynamicText(String text) {
    setString(
      "draft_dynamic_text${AccountStorage().getCurrentUser()?.userProfile?.account}",
      text,
    );
  }
}
