import 'dart:io';
import 'package:flutter/material.dart';
import '../../theme/app_colors.dart';
import '../version_checker.dart';
import '../download_manager.dart';
import '../apk_installer.dart';
import '../app_market_detector.dart';
import '../models/version_info.dart';

/// 自建服务器更新器
/// 负责从自建服务器下载 APK 并安装
class SelfHostedUpdater {
  final VersionChecker versionChecker;
  final DownloadManager downloadManager;

  SelfHostedUpdater({
    required String apiBaseUrl,
  })  : versionChecker = VersionChecker(apiBaseUrl: apiBaseUrl),
        downloadManager = DownloadManager();

  /// 检查并提示更新
  Future<void> checkAndPromptUpdate(BuildContext context) async {
    debugPrint('[SelfHostedUpdater] 开始检查更新...');
    final versionInfo = await versionChecker.checkForUpdate();

    if (versionInfo == null) {
      debugPrint('[SelfHostedUpdater] 已是最新版本，无需更新');
      return;
    }

    debugPrint('[SelfHostedUpdater] 发现新版本: ${versionInfo.version}');

    if (!context.mounted) return;

    // 检测安装来源
    final isFromMarket = await AppMarketDetector.isFromAppMarket();

    if (!context.mounted) return;

    if (isFromMarket) {
      _showMarketUpdateDialog(context, versionInfo);
    } else {
      _showSelfHostedUpdateDialog(context, versionInfo);
    }
  }

  /// 静默检查更新（不显示对话框）
  Future<VersionInfo?> silentCheckUpdate() async {
    return await versionChecker.checkForUpdate();
  }

  /// 应用市场更新提示
  void _showMarketUpdateDialog(BuildContext context, VersionInfo versionInfo) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => PopScope(
        canPop: false,
        child: AlertDialog(
          title: Text(
            versionInfo.forceUpdate ? '发现重要更新' : '发现新版本',
            style: const TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
            ),
          ),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '最新版本: ${versionInfo.version}',
                  style: const TextStyle(
                    fontSize: 14,
                    color: AppColors.textSecondary,
                  ),
                ),
                if (versionInfo.updateLog != null) ...[
                  const SizedBox(height: 16),
                  const Text(
                    '更新内容:',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    versionInfo.updateLog!,
                    style: const TextStyle(
                      fontSize: 14,
                      color: AppColors.textSecondary,
                    ),
                  ),
                ],
                const SizedBox(height: 16),
                const Text(
                  '检测到您的应用来自应用市场，建议前往应用市场更新以获得最佳体验。',
                  style: TextStyle(
                    fontSize: 12,
                    color: AppColors.textMuted,
                  ),
                ),
              ],
            ),
          ),
          actions: [
            if (!versionInfo.forceUpdate)
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('稍后'),
              ),
            FilledButton(
              onPressed: () async {
                Navigator.pop(context);
                final packageInfo =
                    await versionChecker.getCurrentVersion();
                await AppMarketDetector.openAppMarketDetail(
                    packageInfo.packageName);
              },
              child: const Text('前往应用市场'),
            ),
          ],
        ),
      ),
    );
  }

  /// 自建更新对话框
  void _showSelfHostedUpdateDialog(
      BuildContext context, VersionInfo versionInfo) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => PopScope(
        canPop: false,
        child: AlertDialog(
          title: Text(
            versionInfo.forceUpdate ? '发现重要更新' : '发现新版本',
            style: const TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
            ),
          ),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '最新版本: ${versionInfo.version}',
                  style: const TextStyle(
                    fontSize: 14,
                    color: AppColors.textSecondary,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  '文件大小: ${versionInfo.fileSizeFriendly}',
                  style: const TextStyle(
                    fontSize: 14,
                    color: AppColors.textSecondary,
                  ),
                ),
                if (versionInfo.updateLog != null) ...[
                  const SizedBox(height: 16),
                  const Text(
                    '更新内容:',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    versionInfo.updateLog!,
                    style: const TextStyle(
                      fontSize: 14,
                      color: AppColors.textSecondary,
                    ),
                  ),
                ],
              ],
            ),
          ),
          actions: [
            if (!versionInfo.forceUpdate)
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('暂时不更新'),
              ),
            FilledButton(
              onPressed: () {
                Navigator.pop(context);
                _startUpdate(context, versionInfo);
              },
              child: const Text('立即更新'),
            ),
          ],
        ),
      ),
    );
  }

  /// 开始下载并安装
  Future<void> _startUpdate(
      BuildContext context, VersionInfo versionInfo) async {
    if (!context.mounted) return;

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => _DownloadProgressDialog(
        versionInfo: versionInfo,
        downloadManager: downloadManager,
        forceUpdate: versionInfo.forceUpdate,
      ),
    );
  }

  /// 清理下载的 APK
  Future<void> cleanup() async {
    await downloadManager.cleanupDownloadedApk();
  }
}

/// 下载进度对话框
class _DownloadProgressDialog extends StatefulWidget {
  final VersionInfo versionInfo;
  final DownloadManager downloadManager;
  final bool forceUpdate;

  const _DownloadProgressDialog({
    required this.versionInfo,
    required this.downloadManager,
    required this.forceUpdate,
  });

  @override
  State<_DownloadProgressDialog> createState() =>
      _DownloadProgressDialogState();
}

class _DownloadProgressDialogState extends State<_DownloadProgressDialog> {
  double _progress = 0.0;
  String _statusText = '准备下载...';
  bool _isDownloading = true;
  bool _hasError = false;
  bool _downloadCompleted = false;
  File? _downloadedApkFile;

  @override
  void initState() {
    super.initState();
    _startDownload();
  }

  Future<void> _startDownload() async {
    setState(() {
      _statusText = '正在下载...';
      _isDownloading = true;
      _hasError = false;
      _downloadCompleted = false;
    });

    final apkFile = await widget.downloadManager.downloadApk(
      url: widget.versionInfo.downloadUrl,
      sha256Expected: widget.versionInfo.sha256,
      onProgress: (received, total) {
        if (mounted) {
          setState(() {
            _progress = received / total;
            final receivedMB = (received / 1024 / 1024).toStringAsFixed(1);
            final totalMB = (total / 1024 / 1024).toStringAsFixed(1);
            _statusText = '正在下载... $receivedMB MB / $totalMB MB';
          });
        }
      },
    );

    if (!mounted) return;

    if (apkFile == null) {
      setState(() {
        _statusText =
            widget.downloadManager.status == DownloadStatus.cancelled
                ? '下载已取消'
                : '下载失败，请稍后重试';
        _isDownloading = false;
        _hasError = true;
      });
      return;
    }

    _downloadedApkFile = apkFile;

    if (widget.forceUpdate) {
      setState(() {
        _statusText = '下载完成，准备安装...';
      });
      await Future.delayed(const Duration(milliseconds: 500));
      await _installApk();
    } else {
      setState(() {
        _statusText = '下载完成';
        _isDownloading = false;
        _downloadCompleted = true;
      });
    }
  }

  Future<void> _installApk() async {
    if (_downloadedApkFile == null) return;

    setState(() {
      _statusText = '正在安装...';
      _isDownloading = true;
    });

    final installed = await ApkInstaller.installApk(_downloadedApkFile!);

    if (!mounted) return;

    if (installed) {
      Navigator.pop(context);
    } else {
      setState(() {
        _statusText = '安装失败，请手动安装';
        _isDownloading = false;
        _hasError = true;
      });
    }
  }

  void _cancelDownload() {
    widget.downloadManager.cancelDownload();
  }

  void _retryDownload() {
    widget.downloadManager.reset();
    _startDownload();
  }

  @override
  Widget build(BuildContext context) {
    String title;
    if (_downloadCompleted && !_hasError) {
      title = '下载完成';
    } else if (_hasError) {
      title = '更新失败';
    } else {
      title = '正在更新';
    }

    return PopScope(
      canPop: !_isDownloading && !widget.forceUpdate,
      child: AlertDialog(
        title: Text(
          title,
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            LinearProgressIndicator(
              value: _progress,
              valueColor: AlwaysStoppedAnimation<Color>(
                _hasError ? AppColors.error : AppColors.info,
              ),
            ),
            const SizedBox(height: 16),
            Text(
              _statusText,
              style: TextStyle(
                fontSize: 14,
                color: _hasError
                    ? AppColors.error
                    : AppColors.textSecondary,
              ),
            ),
            if (_isDownloading) ...[
              const SizedBox(height: 8),
              Text(
                '${(_progress * 100).toStringAsFixed(0)}%',
                style: const TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.w700,
                  color: AppColors.info,
                ),
              ),
            ],
          ],
        ),
        actions: [
          if (_isDownloading)
            TextButton(
              onPressed: _cancelDownload,
              child: const Text('取消'),
            ),
          if (!_isDownloading && _hasError) ...[
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('关闭'),
            ),
            FilledButton(
              onPressed: _retryDownload,
              child: const Text('重试'),
            ),
          ],
          if (_downloadCompleted && !_hasError) ...[
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('稍后安装'),
            ),
            FilledButton(
              onPressed: _installApk,
              child: const Text('立即安装'),
            ),
          ],
        ],
      ),
    );
  }
}
