import 'package:flutter/material.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}');
  }

  /// 检查更新（自动显示对话框）
  Future<void> checkForUpdate(BuildContext context) async {
    if (!_isInitialized || !_config.enabled) return;

    _isShowingUpdateDialog = true;
    try {
      switch (_config.channel) {
        case UpdateChannel.googlePlay:
          // Google Play 暂不支持，留作扩展
          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();
    }

    return null;
  }

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

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

    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(
        const SnackBar(
          content: Text('当前已是最新版本'),
          backgroundColor: Color(0xFF22C55E),
          duration: Duration(seconds: 2),
        ),
      );
    } else {
      await checkForUpdate(context);
    }
  }

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