import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'channels/google_play_updater.dart';
import 'channels/self_hosted_updater.dart';
import 'models/update_config.dart';
import 'models/version_info.dart';

/// 统一升级服务
/// 根据配置自动选择合适的升级渠道
class UpdateService {
  static UpdateService? _instance;
  UpdateService._();

  factory UpdateService() {
    _instance ??= UpdateService._();
    return _instance!;
  }

  late UpdateConfig _config;
  SelfHostedUpdater? _selfHostedUpdater;
  bool _isInitialized = false;
  bool _isShowingUpdateDialog = false;

  /// 是否已初始化
  bool get isInitialized => _isInitialized;

  /// 是否正在显示升级弹窗
  bool get isShowingUpdateDialog => _isShowingUpdateDialog;

  /// 当前配置
  UpdateConfig get config => _config;

  /// 初始化
  void initialize(UpdateConfig config) {
    _config = config;

    if (config.channel == UpdateChannel.selfHosted) {
      if (config.apiBaseUrl == null) {
        throw ArgumentError('apiBaseUrl is required for self-hosted channel');
      }
      _selfHostedUpdater = SelfHostedUpdater(apiBaseUrl: config.apiBaseUrl!);
    }

    _isInitialized = true;
    debugPrint('UpdateService initialized with channel: ${_config.channel}');
  }

  /// 更新配置
  void updateConfig(UpdateConfig config) {
    _config = config;

    if (config.channel == UpdateChannel.selfHosted && config.apiBaseUrl != null) {
      _selfHostedUpdater = SelfHostedUpdater(apiBaseUrl: config.apiBaseUrl!);
    }

    debugPrint('UpdateService config updated');
  }

  /// 检查更新（自动显示对话框）
  Future<void> checkForUpdate(BuildContext context) async {
    if (!_isInitialized) {
      debugPrint('UpdateService not initialized');
      return;
    }

    if (!_config.enabled) {
      debugPrint('Update check is disabled');
      return;
    }

    _isShowingUpdateDialog = true;
    try {
      switch (_config.channel) {
        case UpdateChannel.googlePlay:
          await _checkGooglePlayUpdate(context);
          break;
        case UpdateChannel.selfHosted:
          await _selfHostedUpdater!.checkAndPromptUpdate(context);
          break;
      }
    } finally {
      _isShowingUpdateDialog = false;
    }
  }

  /// 静默检查更新（不显示对话框）
  Future<VersionInfo?> silentCheck() async {
    if (!_isInitialized || !_config.enabled) {
      return null;
    }

    if (_config.channel == UpdateChannel.selfHosted) {
      return await _selfHostedUpdater?.silentCheckUpdate();
    }

    // Google Play 没有静默检查，返回 null
    return null;
  }

  /// Google Play 更新检查
  Future<void> _checkGooglePlayUpdate(BuildContext context) async {
    final hasUpdate = await GooglePlayUpdater.checkForUpdate();

    if (!hasUpdate) {
      debugPrint('No update available');
      return;
    }

    if (!context.mounted) return;

    await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => PopScope(
        canPop: false,
        child: AlertDialog(
          title: Text(
            '发现新版本',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              color: const Color(0xFF292524),
            ),
          ),
          content: Text(
            '有新版本可用，是否立即更新？',
            style: TextStyle(
              fontSize: 14.sp,
              color: const Color(0xFF57534E),
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text(
                '稍后',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: const Color(0xFF78716C),
                ),
              ),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.pop(context);
                GooglePlayUpdater.performFlexibleUpdate();
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFD4A84B),
                foregroundColor: Colors.white,
              ),
              child: Text(
                '更新',
                style: TextStyle(fontSize: 14.sp),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 手动检查更新（带加载提示）
  Future<void> manualCheckUpdate(BuildContext context) async {
    if (!_isInitialized) {
      debugPrint('UpdateService not initialized');
      return;
    }

    // 显示加载中
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(
          color: Color(0xFFD4A84B),
        ),
      ),
    );

    await Future.delayed(const Duration(seconds: 1));

    if (!context.mounted) return;
    Navigator.pop(context);

    // 检查是否有更新
    final versionInfo = await silentCheck();

    if (!context.mounted) return;

    if (versionInfo == null) {
      // 没有更新
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            '当前已是最新版本',
            style: TextStyle(fontSize: 14.sp),
          ),
          backgroundColor: const Color(0xFF22C55E),
          duration: const Duration(seconds: 2),
        ),
      );
    } else {
      // 有更新，显示对话框
      await checkForUpdate(context);
    }
  }

  /// 执行强制更新
  Future<void> performForceUpdate(BuildContext context) async {
    if (!_isInitialized) return;

    switch (_config.channel) {
      case UpdateChannel.googlePlay:
        await GooglePlayUpdater.performImmediateUpdate();
        break;
      case UpdateChannel.selfHosted:
        await _selfHostedUpdater?.checkAndPromptUpdate(context);
        break;
    }
  }

  /// 清理缓存的更新文件
  Future<void> cleanup() async {
    await _selfHostedUpdater?.cleanup();
  }

  /// 重置实例
  static void reset() {
    _instance = null;
  }
}
