import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import '../models/version_info.dart';
import '../download_manager.dart';
import '../update_service.dart';

/// 自托管更新弹窗
/// 用于展示更新信息和下载进度
class SelfHostedUpdater extends StatefulWidget {
  final VersionInfo versionInfo;
  final bool isForceUpdate;
  final VoidCallback? onDismiss;
  final VoidCallback? onInstalled;

  const SelfHostedUpdater({
    super.key,
    required this.versionInfo,
    this.isForceUpdate = false,
    this.onDismiss,
    this.onInstalled,
  });

  /// 显示更新弹窗
  static Future<void> show(
    BuildContext context, {
    required VersionInfo versionInfo,
    bool isForceUpdate = false,
    VoidCallback? onDismiss,
    VoidCallback? onInstalled,
  }) async {
    await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => SelfHostedUpdater(
        versionInfo: versionInfo,
        isForceUpdate: isForceUpdate,
        onDismiss: onDismiss,
        onInstalled: onInstalled,
      ),
    );
  }

  @override
  State<SelfHostedUpdater> createState() => _SelfHostedUpdaterState();
}

class _SelfHostedUpdaterState extends State<SelfHostedUpdater> {
  DownloadProgress _progress = DownloadProgress.initial();
  File? _downloadedFile;
  bool _isDownloading = false;
  StreamSubscription<DownloadProgress>? _progressSubscription;

  @override
  void initState() {
    super.initState();
    // 订阅持久化广播流，无论何时开始下载都能收到进度
    _progressSubscription = UpdateService.instance.downloadProgressStream.listen((progress) {
      if (mounted) {
        setState(() {
          _progress = progress;
        });
      }
    });
  }

  @override
  void dispose() {
    _progressSubscription?.cancel();
    super.dispose();
  }

  Future<void> _startDownload() async {
    setState(() {
      _isDownloading = true;
      _progress = DownloadProgress.initial().copyWith(
        status: DownloadStatus.downloading,
      );
    });

    final file = await UpdateService.instance.downloadUpdate(widget.versionInfo);

    if (mounted) {
      setState(() {
        _downloadedFile = file;
        _isDownloading = false;
      });

      if (file != null) {
        _installApk(file);
      }
    }
  }

  Future<void> _installApk(File file) async {
    final success = await UpdateService.instance.installUpdate(file);
    if (success) {
      widget.onInstalled?.call();
    }
  }

  void _cancelDownload() {
    UpdateService.instance.cancelDownload();
    setState(() {
      _isDownloading = false;
      _progress = DownloadProgress.initial();
    });
  }

  @override
  Widget build(BuildContext context) {
    // 使用 PopScope 替代已废弃的 WillPopScope
    // canPop: false 表示禁止返回（强制更新时）
    return PopScope(
      canPop: !widget.isForceUpdate,
      child: AlertDialog(
        title: const Text('发现新版本'),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 版本信息
              _buildVersionInfo(),
              const SizedBox(height: 16),

              // 更新日志
              _buildChangelog(),
              const SizedBox(height: 16),

              // 下载进度
              if (_isDownloading || _progress.status != DownloadStatus.idle)
                _buildDownloadProgress(),
            ],
          ),
        ),
        actions: _buildActions(),
      ),
    );
  }

  Widget _buildVersionInfo() {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surfaceContainerHighest,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '版本 ${widget.versionInfo.versionName}',
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
              if (widget.isForceUpdate)
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                  decoration: BoxDecoration(
                    color: Colors.red,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: const Text(
                    '强制更新',
                    style: TextStyle(color: Colors.white, fontSize: 12),
                  ),
                ),
            ],
          ),
          const SizedBox(height: 4),
          Text(
            '文件大小: ${widget.versionInfo.formattedFileSize}',
            style: TextStyle(
              color: Theme.of(context).colorScheme.onSurfaceVariant,
              fontSize: 13,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildChangelog() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '更新内容',
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 8),
        Container(
          constraints: const BoxConstraints(maxHeight: 150),
          child: SingleChildScrollView(
            child: Text(
              widget.versionInfo.changelog,
              style: TextStyle(
                color: Theme.of(context).colorScheme.onSurfaceVariant,
                fontSize: 13,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildDownloadProgress() {
    String statusText;
    switch (_progress.status) {
      case DownloadStatus.downloading:
        statusText = '下载中 ${_progress.progressText}';
        break;
      case DownloadStatus.verifying:
        statusText = '验证文件中...';
        break;
      case DownloadStatus.completed:
        statusText = '下载完成';
        break;
      case DownloadStatus.failed:
        statusText = '下载失败: ${_progress.error ?? "未知错误"}';
        break;
      default:
        statusText = '准备下载...';
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(statusText, style: const TextStyle(fontSize: 13)),
        const SizedBox(height: 8),
        LinearProgressIndicator(
          value: _progress.status == DownloadStatus.verifying
              ? null
              : _progress.progress,
        ),
      ],
    );
  }

  List<Widget> _buildActions() {
    if (_progress.status == DownloadStatus.completed && _downloadedFile != null) {
      return [
        TextButton(
          onPressed: () => _installApk(_downloadedFile!),
          child: const Text('立即安装'),
        ),
      ];
    }

    if (_isDownloading) {
      return [
        TextButton(
          onPressed: _cancelDownload,
          child: const Text('取消'),
        ),
      ];
    }

    return [
      if (!widget.isForceUpdate)
        TextButton(
          onPressed: () {
            Navigator.of(context).pop();
            widget.onDismiss?.call();
          },
          child: const Text('稍后再说'),
        ),
      ElevatedButton(
        onPressed: _startDownload,
        child: const Text('立即更新'),
      ),
    ];
  }
}
