import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../services/maintenance_service.dart';

/// 系统维护状态 Provider
///
/// 负责：
/// 1. 检查系统维护状态
/// 2. 监听 App 生命周期变化（后台切回时自动检查）
/// 3. 定时刷新维护状态
/// 4. 提供全局维护弹窗显示控制
class MaintenanceNotifier extends StateNotifier<MaintenanceStatus>
    with WidgetsBindingObserver {
  static const _checkIntervalSeconds = 60; // 维护期间每 60 秒检查一次是否结束

  Timer? _checkTimer;
  bool _isDialogShowing = false;
  BuildContext? _dialogContext;

  /// 全局导航 Key，用于在生命周期事件中显示弹窗
  GlobalKey<NavigatorState>? _navigatorKey;

  MaintenanceNotifier() : super(MaintenanceStatus.normal) {
    WidgetsBinding.instance.addObserver(this);
    // 初始化服务
    MaintenanceService().initialize();
  }

  /// 设置全局导航 Key
  void setNavigatorKey(GlobalKey<NavigatorState> key) {
    _navigatorKey = key;
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _checkTimer?.cancel();
    super.dispose();
  }

  /// 监听 App 生命周期变化
  @override
  void didChangeAppLifecycleState(AppLifecycleState lifecycleState) {
    if (lifecycleState == AppLifecycleState.resumed) {
      // App 从后台切回前台，立即检查维护状态
      _checkAndShowDialogIfNeeded();
    }
  }

  /// 检查维护状态并在必要时显示弹窗
  Future<void> _checkAndShowDialogIfNeeded() async {
    final status = await checkMaintenanceStatus();

    if (status.isUnderMaintenance && status.maintenance != null && !_isDialogShowing) {
      // 优先使用全局导航 Key
      final context = _navigatorKey?.currentContext;
      if (context != null) {
        _showMaintenanceDialog(context, status.maintenance!);
      }
    }
  }

  /// 检查系统维护状态
  ///
  /// 如果处于维护状态，会自动启动定时检查
  Future<MaintenanceStatus> checkMaintenanceStatus() async {
    try {
      final status = await MaintenanceService().checkStatus();
      state = status;

      if (status.isUnderMaintenance) {
        debugPrint('[MaintenanceProvider] 检测到系统维护中');
        _startPeriodicCheck();
      } else {
        _stopPeriodicCheck();
        // 如果之前在维护，现在恢复了，关闭弹窗
        if (_isDialogShowing) {
          _dismissMaintenanceDialog();
        }
      }

      return status;
    } catch (e) {
      debugPrint('[MaintenanceProvider] 检查维护状态失败: $e');
      return MaintenanceStatus.normal;
    }
  }

  /// 启动定时检查（维护期间持续检查是否已恢复）
  void _startPeriodicCheck() {
    _checkTimer?.cancel();
    _checkTimer = Timer.periodic(
      const Duration(seconds: _checkIntervalSeconds),
      (_) => checkMaintenanceStatus(),
    );
  }

  /// 停止定时检查
  void _stopPeriodicCheck() {
    _checkTimer?.cancel();
    _checkTimer = null;
  }

  /// 显示维护弹窗（全局阻断）
  ///
  /// 返回 true 表示正在维护并已显示弹窗
  /// 返回 false 表示系统正常，无需阻断
  Future<bool> showMaintenanceDialogIfNeeded(BuildContext context) async {
    final status = await checkMaintenanceStatus();

    if (status.isUnderMaintenance && status.maintenance != null) {
      _showMaintenanceDialog(context, status.maintenance!);
      return true;
    }

    return false;
  }

  /// 显示维护弹窗
  void _showMaintenanceDialog(BuildContext context, MaintenanceInfo info) {
    if (_isDialogShowing) return;

    _isDialogShowing = true;
    _dialogContext = context;

    showDialog(
      context: context,
      barrierDismissible: false, // 不可点击外部关闭
      barrierColor: Colors.black87, // 深色遮罩
      builder: (dialogContext) => PopScope(
        canPop: false, // 禁用返回键
        child: MaintenanceDialog(
          info: info,
          onRefresh: () async {
            final status = await checkMaintenanceStatus();
            if (!status.isUnderMaintenance) {
              _dismissMaintenanceDialog();
            }
          },
        ),
      ),
    ).then((_) {
      _isDialogShowing = false;
      _dialogContext = null;
    });
  }

  /// 关闭维护弹窗
  void _dismissMaintenanceDialog() {
    if (_isDialogShowing && _dialogContext != null) {
      Navigator.of(_dialogContext!, rootNavigator: true).pop();
      _isDialogShowing = false;
      _dialogContext = null;
    }
  }
}

/// 系统维护 Provider
final maintenanceProvider =
    StateNotifierProvider<MaintenanceNotifier, MaintenanceStatus>((ref) {
  return MaintenanceNotifier();
});

/// 便捷 Provider: 只获取是否正在维护
final isUnderMaintenanceProvider = Provider<bool>((ref) {
  return ref.watch(maintenanceProvider).isUnderMaintenance;
});

/// 维护弹窗组件
class MaintenanceDialog extends StatefulWidget {
  final MaintenanceInfo info;
  final VoidCallback? onRefresh;

  const MaintenanceDialog({
    super.key,
    required this.info,
    this.onRefresh,
  });

  @override
  State<MaintenanceDialog> createState() => _MaintenanceDialogState();
}

class _MaintenanceDialogState extends State<MaintenanceDialog> {
  bool _isRefreshing = false;
  late int _remainingMinutes;

  @override
  void initState() {
    super.initState();
    _remainingMinutes = widget.info.remainingMinutes;
    // 每分钟更新剩余时间
    _startCountdown();
  }

  void _startCountdown() {
    Future.delayed(const Duration(minutes: 1), () {
      if (mounted && _remainingMinutes > 0) {
        setState(() {
          _remainingMinutes--;
        });
        _startCountdown();
      }
    });
  }

  Future<void> _handleRefresh() async {
    if (_isRefreshing) return;

    setState(() {
      _isRefreshing = true;
    });

    widget.onRefresh?.call();

    // 延迟一下再恢复按钮状态
    await Future.delayed(const Duration(seconds: 2));

    if (mounted) {
      setState(() {
        _isRefreshing = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.transparent,
      elevation: 0,
      child: Container(
        width: 320,
        padding: const EdgeInsets.all(24),
        decoration: BoxDecoration(
          color: const Color(0xFFFFFBF5),
          borderRadius: BorderRadius.circular(20),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withValues(alpha: 0.2),
              blurRadius: 20,
              offset: const Offset(0, 10),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 维护图标
            Container(
              width: 80,
              height: 80,
              decoration: BoxDecoration(
                color: const Color(0xFFD4AF37).withValues(alpha: 0.1),
                shape: BoxShape.circle,
              ),
              child: const Center(
                child: Text(
                  '🔧',
                  style: TextStyle(fontSize: 40),
                ),
              ),
            ),
            const SizedBox(height: 20),

            // 标题
            Text(
              widget.info.title,
              style: const TextStyle(
                fontSize: 20,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w700,
                color: Color(0xFF5D4037),
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 12),

            // 消息内容
            Text(
              widget.info.message,
              style: const TextStyle(
                fontSize: 14,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w400,
                color: Color(0xFF8B7355),
                height: 1.5,
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 20),

            // 剩余时间
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
              decoration: BoxDecoration(
                color: const Color(0xFFD4AF37).withValues(alpha: 0.15),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(
                    Icons.access_time,
                    size: 18,
                    color: Color(0xFFD4AF37),
                  ),
                  const SizedBox(width: 8),
                  Text(
                    _remainingMinutes > 0
                        ? '预计剩余 $_remainingMinutes 分钟'
                        : '即将恢复...',
                    style: const TextStyle(
                      fontSize: 14,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w600,
                      color: Color(0xFFD4AF37),
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 24),

            // 刷新按钮
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: _isRefreshing ? null : _handleRefresh,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFFD4AF37),
                  foregroundColor: Colors.white,
                  disabledBackgroundColor: const Color(0xFFD4AF37).withValues(alpha: 0.5),
                  padding: const EdgeInsets.symmetric(vertical: 14),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  elevation: 0,
                ),
                child: _isRefreshing
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor:
                              AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      )
                    : const Text(
                        '刷新状态',
                        style: TextStyle(
                          fontSize: 16,
                          fontFamily: 'Inter',
                          fontWeight: FontWeight.w600,
                        ),
                      ),
              ),
            ),
            const SizedBox(height: 12),

            // 提示文字
            const Text(
              '感谢您的耐心等待',
              style: TextStyle(
                fontSize: 12,
                fontFamily: 'Inter',
                color: Color(0xFFBDBDBD),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
