import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../shared/providers/auth_provider.dart';
import '../../shared/providers/vocabulary_provider.dart';
import '../../shared/services/auth_service.dart';
import '../../shared/services/vocabulary_service.dart';
import '../network/api_client.dart';

/// 全局应用状态管理
class AppStateNotifier extends StateNotifier<AppState> {
  AppStateNotifier() : super(const AppState());

  void updateTheme(ThemeMode themeMode) {
    state = state.copyWith(themeMode: themeMode);
  }

  void updateLocale(String locale) {
    state = state.copyWith(locale: locale);
  }

  void updateNetworkStatus(bool isOnline) {
    state = state.copyWith(isOnline: isOnline);
  }

  void updateLoading(bool isLoading) {
    state = state.copyWith(isGlobalLoading: isLoading);
  }
}

/// 应用状态模型
class AppState {
  final ThemeMode themeMode;
  final String locale;
  final bool isOnline;
  final bool isGlobalLoading;

  const AppState({
    this.themeMode = ThemeMode.light,
    this.locale = 'zh_CN',
    this.isOnline = true,
    this.isGlobalLoading = false,
  });

  AppState copyWith({
    ThemeMode? themeMode,
    String? locale,
    bool? isOnline,
    bool? isGlobalLoading,
  }) {
    return AppState(
      themeMode: themeMode ?? this.themeMode,
      locale: locale ?? this.locale,
      isOnline: isOnline ?? this.isOnline,
      isGlobalLoading: isGlobalLoading ?? this.isGlobalLoading,
    );
  }
}

/// 全局状态Provider
final appStateProvider = StateNotifierProvider<AppStateNotifier, AppState>(
  (ref) => AppStateNotifier(),
);

/// API客户端Provider
final apiClientProvider = Provider<ApiClient>(
  (ref) => ApiClient.instance,
);

/// 认证服务Provider
final authServiceProvider = Provider<AuthService>(
  (ref) => AuthService(),
);

/// 词汇服务Provider
final vocabularyServiceProvider = Provider<VocabularyService>(
  (ref) => VocabularyService(),
);

/// 认证Provider
final authProvider = ChangeNotifierProvider<AuthProvider>(
  (ref) {
    final authService = ref.read(authServiceProvider);
    return AuthProvider()..initialize();
  },
);

/// 词汇Provider
final vocabularyProvider = ChangeNotifierProvider<VocabularyProvider>(
  (ref) {
    final vocabularyService = ref.read(vocabularyServiceProvider);
    return VocabularyProvider(vocabularyService);
  },
);

/// 网络状态Provider
final networkStatusProvider = StreamProvider<bool>(
  (ref) async* {
    // 这里可以实现网络状态监听
    yield true; // 默认在线状态
  },
);

/// 缓存管理Provider
final cacheManagerProvider = Provider<CacheManager>(
  (ref) => CacheManager(),
);

/// 缓存管理器
class CacheManager {
  final Map<String, dynamic> _cache = {};
  final Map<String, DateTime> _cacheTimestamps = {};
  final Duration _defaultCacheDuration = const Duration(minutes: 30);

  /// 设置缓存
  void set(String key, dynamic value, {Duration? duration}) {
    _cache[key] = value;
    _cacheTimestamps[key] = DateTime.now();
  }

  /// 获取缓存
  T? get<T>(String key, {Duration? duration}) {
    final timestamp = _cacheTimestamps[key];
    if (timestamp == null) return null;

    final cacheDuration = duration ?? _defaultCacheDuration;
    if (DateTime.now().difference(timestamp) > cacheDuration) {
      remove(key);
      return null;
    }

    return _cache[key] as T?;
  }

  /// 移除缓存
  void remove(String key) {
    _cache.remove(key);
    _cacheTimestamps.remove(key);
  }

  /// 清空缓存
  void clear() {
    _cache.clear();
    _cacheTimestamps.clear();
  }

  /// 检查缓存是否存在且有效
  bool isValid(String key, {Duration? duration}) {
    final timestamp = _cacheTimestamps[key];
    if (timestamp == null) return false;

    final cacheDuration = duration ?? _defaultCacheDuration;
    return DateTime.now().difference(timestamp) <= cacheDuration;
  }
}