import 'package:flutter/material.dart';
import '../../app/i18n/app_localizations.dart';
import '../../app/theme/app_colors.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: ${_config.channel}');
  }

  Future<void> checkForUpdate(BuildContext context) async {
    if (!_isInitialized || !_config.enabled) 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();
    }
    return null;
  }

  Future<void> _checkGooglePlayUpdate(BuildContext context) async {
    final hasUpdate = await GooglePlayUpdater.checkForUpdate();
    if (!hasUpdate || !context.mounted) return;

    await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(
          context.t('update.newVersion'),
          style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
        ),
        content: Text(
          context.t('update.updateNow'),
          style: TextStyle(fontSize: 14, color: Colors.grey[700]),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              context.t('update.later'),
              style: TextStyle(fontSize: 14, color: Colors.grey[600]),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              GooglePlayUpdater.performFlexibleUpdate();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.primary,
              foregroundColor: Colors.white,
            ),
            child: Text(context.t('update.updateNow'), style: const TextStyle(fontSize: 14)),
          ),
        ],
      ),
    );
  }

  Future<void> manualCheckUpdate(BuildContext context) async {
    if (!_isInitialized) return;

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => const Center(child: CircularProgressIndicator(color: AppColors.primary)),
    );

    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(context.t('update.isLatest')),
          backgroundColor: AppColors.success,
          duration: const Duration(seconds: 2),
        ),
      );
    } else {
      await checkForUpdate(context);
    }
  }

  Future<void> cleanup() async {
    await _selfHostedUpdater?.cleanup();
  }

  static void reset() {
    _instance = null;
  }
}
