import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../../core/theme/app_colors.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/contract_check_service.dart';
import '../../../../core/updater/update_service.dart';
import '../../../../core/providers/maintenance_provider.dart';
import '../../../../routes/route_paths.dart';
import '../../../../routes/app_router.dart';
import '../../../../bootstrap.dart';
import '../../../../core/providers/notification_badge_provider.dart';
import '../widgets/bottom_nav_bar.dart';

class HomeShellPage extends ConsumerStatefulWidget {
  final Widget child;

  const HomeShellPage({super.key, required this.child});

  @override
  ConsumerState<HomeShellPage> createState() => _HomeShellPageState();
}

class _HomeShellPageState extends ConsumerState<HomeShellPage>
    with WidgetsBindingObserver {
  /// 下次允许检查更新的时间
  static DateTime? _nextCheckAllowedTime;

  /// 是否已检查过合同（防止重复检查）
  static bool _hasCheckedContracts = false;

  /// 后台合同检查定时器
  Timer? _contractCheckTimer;

  /// 维护状态检查定时器
  Timer? _maintenanceCheckTimer;

  /// 是否正在显示弹窗（防止重复弹窗）
  bool _isShowingDialog = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    // 首次进入时检查维护状态、更新和未签署合同
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _checkMaintenanceStatus();
      _checkForUpdateIfNeeded();
      _checkContractsAndKyc();
      // 启动后台定时检查
      _startBackgroundContractCheck();
      // 启动维护状态定时检查
      _startMaintenanceCheck();
    });
  }

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

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // 从后台恢复时检查维护状态和更新
    if (state == AppLifecycleState.resumed) {
      _checkMaintenanceStatus();
      _checkForUpdateIfNeeded();
      // 从后台恢复时也触发一次检查
      _scheduleNextContractCheck();
      // 恢复维护检查定时器
      _startMaintenanceCheck();
    } else if (state == AppLifecycleState.paused) {
      // 进入后台时取消定时器
      _contractCheckTimer?.cancel();
      _maintenanceCheckTimer?.cancel();
    }
  }

  /// 启动维护状态定时检查（随机 30-60 秒检查一次）
  void _startMaintenanceCheck() {
    _scheduleNextMaintenanceCheck();
  }

  /// 安排下一次维护检查
  void _scheduleNextMaintenanceCheck() {
    _maintenanceCheckTimer?.cancel();
    // 随机 30-60 秒，平衡及时性和服务器压力
    final randomSeconds = 30 + Random().nextInt(31); // 30 + 0~30 = 30~60
    _maintenanceCheckTimer = Timer(Duration(seconds: randomSeconds), () async {
      await _checkMaintenanceStatus();
      // 检查完成后安排下一次检查
      if (mounted) {
        _scheduleNextMaintenanceCheck();
      }
    });
  }

  /// 检查系统维护状态
  Future<void> _checkMaintenanceStatus() async {
    if (!mounted) return;

    try {
      final maintenanceNotifier = ref.read(maintenanceProvider.notifier);
      await maintenanceNotifier.showMaintenanceDialogIfNeeded(context);
    } catch (e) {
      debugPrint('[HomeShellPage] 检查维护状态失败: $e');
    }
  }

  Future<void> _checkForUpdateIfNeeded() async {
    final now = DateTime.now();

    // 如果从未检查过，或者已过冷却时间，则检查
    if (_nextCheckAllowedTime == null || now.isAfter(_nextCheckAllowedTime!)) {
      // 设置下次允许检查时间（90-300秒随机间隔）
      final randomSeconds = 90 + Random().nextInt(211); // 90 + 0~210 = 90~300
      _nextCheckAllowedTime = now.add(Duration(seconds: randomSeconds));
      await checkForAppUpdate(context);
    }
  }

  /// 启动后台合同检查定时器
  void _startBackgroundContractCheck() {
    _scheduleNextContractCheck();
  }

  /// 安排下一次合同检查（随机 5-20 秒）
  void _scheduleNextContractCheck() {
    _contractCheckTimer?.cancel();

    // 随机 5-20 秒
    final randomSeconds = 5 + Random().nextInt(16); // 5 + 0~15 = 5~20

    _contractCheckTimer = Timer(Duration(seconds: randomSeconds), () async {
      await _performBackgroundContractCheck();
      // 检查完成后安排下一次检查
      if (mounted) {
        _scheduleNextContractCheck();
      }
    });
  }

  /// 检查当前是否在合同签署或KYC相关页面，或者正在显示升级弹窗
  bool _shouldSkipContractCheck() {
    // 1. 检查是否正在显示升级弹窗
    if (UpdateService().isShowingUpdateDialog) {
      return true;
    }

    // 2. 检查是否在合同/KYC页面
    // 遍历整个路由栈，检查是否有任何合同/KYC相关页面
    try {
      final router = ref.read(appRouterProvider);
      final matches = router.routerDelegate.currentConfiguration.matches;

      for (final match in matches) {
        final location = match.matchedLocation;
        // 合同签署相关页面
        if (location.startsWith('/contract-signing')) return true;
        // KYC 相关页面
        if (location.startsWith('/kyc')) return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  /// 执行后台综合检查（合同 + KYC）
  Future<void> _performBackgroundContractCheck() async {
    if (!mounted || _isShowingDialog) return;

    // 如果用户在合同签署、KYC页面，或正在升级，跳过检查
    if (_shouldSkipContractCheck()) return;

    try {
      final contractCheckService = ref.read(contractCheckServiceProvider);
      final result = await contractCheckService.checkAll();

      if (!mounted || _isShowingDialog) return;

      // 再次检查，防止在请求期间用户进入了相关页面或开始升级
      if (_shouldSkipContractCheck()) return;

      // 1. 优先处理待签署合同
      if (result.hasPendingContracts) {
        await _showContractRequiredDialog();
        return;
      }

      // 2. 处理需要 KYC 的情况
      if (result.requiresKyc) {
        await _showKycRequiredDialog(result);
      }
    } catch (e) {
      // 静默失败，不阻止用户使用
    }
  }

  /// 综合检查：待签署合同和 KYC 需求
  Future<void> _checkContractsAndKyc() async {
    // 每次会话只检查一次
    if (_hasCheckedContracts) return;
    _hasCheckedContracts = true;

    // 如果用户已在合同/KYC页面，跳过检查
    if (_shouldSkipContractCheck()) return;

    try {
      final contractCheckService = ref.read(contractCheckServiceProvider);
      final result = await contractCheckService.checkAll();

      if (!mounted) return;

      // 再次检查，防止在请求期间用户进入了相关页面
      if (_shouldSkipContractCheck()) return;

      // 1. 优先处理待签署合同
      if (result.hasPendingContracts) {
        // 有待签署合同，跳转到待签署列表页面
        // forceSign=true 表示必须签署后才能继续使用
        context.push(RoutePaths.pendingContracts, extra: true);
        return;
      }

      // 2. 处理需要 KYC 的情况
      if (result.requiresKyc) {
        await _showKycRequiredDialog(result);
      }
    } catch (e) {
      // 检查失败不阻止用户使用 App
    }
  }

  /// 显示合同签署必需弹窗（后台检测触发）
  Future<void> _showContractRequiredDialog() async {
    if (_isShowingDialog) return;
    _isShowingDialog = true;

    const message =
        '系统检测到您已认种了榴莲树，但尚未按国家法规签署合规的认种合同。请先完成合同签署，才能继续使用APP。';

    await showDialog(
      context: context,
      barrierDismissible: false, // 不允许点击外部关闭
      builder: (context) => PopScope(
        canPop: false, // 不允许返回键关闭
        child: AlertDialog(
          title: Row(
            children: [
              Icon(Icons.description_outlined, color: Colors.orange[700], size: 28),
              const SizedBox(width: 8),
              const Text('需要签署合同'),
            ],
          ),
          content: const Text(
            message,
            style: TextStyle(fontSize: 15, height: 1.5),
          ),
          actions: [
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
                _isShowingDialog = false;
                // 跳转到待签署合同列表页面
                context.push(RoutePaths.pendingContracts, extra: true);
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: AppColors.primary,
                foregroundColor: Colors.white,
                minimumSize: const Size(double.infinity, 48),
              ),
              child: const Text('立即签署', style: TextStyle(fontSize: 16)),
            ),
          ],
        ),
      ),
    );

    _isShowingDialog = false;
  }

  /// 显示 KYC 必需弹窗
  Future<void> _showKycRequiredDialog(ContractCheckResult result) async {
    if (_isShowingDialog) return;
    _isShowingDialog = true;

    final message = result.kycMessage ??
        '系统检测到您已认种了榴莲树，但尚未按国家法规完成实名认证，无法签署合同。请先完成实名认证后才能继续使用APP。';

    await showDialog(
      context: context,
      barrierDismissible: false, // 不允许点击外部关闭
      builder: (context) => PopScope(
        canPop: false, // 不允许返回键关闭
        child: AlertDialog(
          title: Row(
            children: [
              Icon(Icons.warning_amber_rounded, color: Colors.orange[700], size: 28),
              const SizedBox(width: 8),
              const Text('需要实名认证'),
            ],
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                message,
                style: const TextStyle(fontSize: 15, height: 1.5),
              ),
              if (result.paidOrderCount > 0) ...[
                const SizedBox(height: 12),
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.orange.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.info_outline, color: Colors.orange[700], size: 20),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          '您有 ${result.paidOrderCount} 笔认种订单待签署合同',
                          style: TextStyle(
                            color: Colors.orange[800],
                            fontSize: 14,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ],
          ),
          actions: [
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
                _isShowingDialog = false;
                // 跳转到 KYC 入口页面
                context.push(RoutePaths.kycEntry);
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: AppColors.primary,
                foregroundColor: Colors.white,
                minimumSize: const Size(double.infinity, 48),
              ),
              child: const Text('立即认证', style: TextStyle(fontSize: 16)),
            ),
          ],
        ),
      ),
    );

    _isShowingDialog = false;
  }

  /// 重置合同检查状态（用于用户切换账号时）
  static void resetContractCheckState() {
    _hasCheckedContracts = false;
  }

  int _getCurrentIndex(BuildContext context) {
    final location = GoRouterState.of(context).uri.path;
    // 索引: 0-龙虎榜, 1-监控, 2-兑换, 3-我
    if (location.startsWith(RoutePaths.ranking)) return 0;
    if (location.startsWith(RoutePaths.mining)) return 1;
    if (location.startsWith(RoutePaths.trading)) return 2;
    if (location.startsWith(RoutePaths.profile)) return 3;
    return 0;
  }

  void _onTabTapped(BuildContext context, int index) {
    // 索引: 0-龙虎榜, 1-监控, 2-兑换, 3-我
    switch (index) {
      case 0:
        context.go(RoutePaths.ranking);
        break;
      case 1:
        context.go(RoutePaths.mining);
        break;
      case 2:
        context.go(RoutePaths.trading);
        break;
      case 3:
        context.go(RoutePaths.profile);
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    final unreadCount = ref.watch(unreadNotificationCountProvider);

    return Scaffold(
      body: widget.child,
      bottomNavigationBar: BottomNavBar(
        currentIndex: _getCurrentIndex(context),
        onTap: (index) => _onTabTapped(context, index),
        profileBadgeCount: unreadCount,
      ),
    );
  }
}
