import 'package:flutter/material.dart';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:permission_handler/permission_handler.dart';
import '../widgets/dialogs/kr_dialog.dart';
import '../localization/app_translations.dart';
import 'dart:io' show Platform;
import 'dart:io' show InternetAddress;

/// 网络检查工具类
class KRNetworkCheck {
  /// 初始化网络检查
  static Future<bool> kr_initialize(BuildContext context, {VoidCallback? onPermissionGranted}) async {
    try {
      if (Platform.isIOS) {
        // iOS 平台特殊处理
        final hasPermission = await kr_checkNetworkPermission();
        if (!hasPermission) {
          // 显示网络设置提示对话框
          final bool? result = await kr_showNetworkDialog();
          if (result == true) {
            // 打开系统设置
            await kr_openAppSettings();
            
            // 等待用户返回并检查权限
            bool hasPermissionAfterSettings = false;
            for (int i = 0; i < 10; i++) {
              await Future.delayed(const Duration(seconds: 1));
              hasPermissionAfterSettings = await kr_checkNetworkPermission();
              if (hasPermissionAfterSettings) {
                onPermissionGranted?.call();
                return true;
              }
            }
            
            if (!hasPermissionAfterSettings) {
              await kr_showNetworkDialog();
              return false;
            }
          }
          return false;
        }
      } else {
        // Android 平台处理
        final hasPermission = await kr_checkNetworkPermission();
        if (!hasPermission) {
          final bool? result = await kr_showNetworkDialog();
          if (result == true) {
            await kr_openAppSettings();
            
            bool hasPermissionAfterSettings = false;
            for (int i = 0; i < 10; i++) {
              await Future.delayed(const Duration(seconds: 1));
              hasPermissionAfterSettings = await kr_checkNetworkPermission();
              if (hasPermissionAfterSettings) {
                onPermissionGranted?.call();
                return true;
              }
            }
            
            if (!hasPermissionAfterSettings) {
              await kr_showNetworkDialog();
              return false;
            }
          }
          return false;
        }
      }

      onPermissionGranted?.call();
      return true;
    } catch (e) {
      debugPrint('网络检查初始化错误: $e');
      return false;
    }
  }

  /// 检查网络权限
  static Future<bool> kr_checkNetworkPermission() async {
    try {
      if (Platform.isIOS) {
        // iOS 平台使用更可靠的方式检查网络状态
        final connectivityResult = await Connectivity().checkConnectivity();
        if (connectivityResult == ConnectivityResult.none) {
          return false;
        }

        // 尝试进行实际的网络请求测试
        try {
          final result = await InternetAddress.lookup('www.apple.com');
          return result.isNotEmpty && result[0].rawAddress.isNotEmpty;
        } catch (e) {
          return false;
        }
      } else {
        // 🔧 Android 15 增强：多重验证网络可用性
        // 1. 检查连接状态（基础检查）
        final connectivityResult = await Connectivity().checkConnectivity().timeout(
          const Duration(seconds: 3),
          onTimeout: () {
            debugPrint('⚠️ 连接性检查超时');
            return ConnectivityResult.none;
          },
        );

        if (connectivityResult == ConnectivityResult.none) {
          debugPrint('❌ 网络未连接');
          return false;
        }

        // 2. 🔧 Android 15 新增：尝试实际 DNS 解析验证网络可用性
        // 这在 Android 15 上很重要，因为系统可能报告网络已连接但实际无法访问
        try {
          final result = await InternetAddress.lookup('www.google.com').timeout(
            const Duration(seconds: 5),
            onTimeout: () {
              debugPrint('⚠️ DNS 解析超时，网络可能不稳定');
              return <InternetAddress>[];
            },
          );

          if (result.isEmpty) {
            debugPrint('⚠️ DNS 解析失败，但允许继续（可能是网络延迟）');
            // 即使 DNS 解析失败，也允许继续，因为可能只是网络延迟
            return true;
          }

          debugPrint('✅ 网络权限检查通过（连接性 + DNS 解析）');
          return true;
        } catch (e) {
          debugPrint('⚠️ DNS 解析异常: $e，但允许继续');
          // DNS 解析异常也允许继续，避免误判
          return true;
        }
      }
    } catch (e) {
      debugPrint('❌ 网络权限检查错误: $e');
      // 🔧 Android 15 优化：出错时返回 true，避免阻塞应用启动
      // 实际网络问题会在后续步骤中处理
      return true;
    }
  }

  /// 检查网络连接状态
  static Future<bool> kr_checkNetworkConnection() async {
    try {
      if (Platform.isIOS) {
        // iOS 平台使用更可靠的方式检查网络状态
        final connectivityResult = await Connectivity().checkConnectivity();
        if (connectivityResult == ConnectivityResult.none) {
          return false;
        }

        try {
          final result = await InternetAddress.lookup('www.apple.com');
          return result.isNotEmpty && result[0].rawAddress.isNotEmpty;
        } catch (e) {
          return false;
        }
      } else {
        // 🔧 Android 15 增强：添加超时保护
        final connectivityResult = await Connectivity().checkConnectivity().timeout(
          const Duration(seconds: 3),
          onTimeout: () {
            debugPrint('⚠️ 网络连接检查超时');
            return ConnectivityResult.none;
          },
        );

        if (connectivityResult == ConnectivityResult.none) {
          debugPrint('❌ 网络未连接');
          return false;
        }

        // 🔧 Android 15 优化：对于已连接的网络，快速返回 true
        // 避免不必要的 DNS 查询延迟应用启动
        debugPrint('✅ 网络连接检查通过（${connectivityResult.name}）');
        return true;
      }
    } catch (e) {
      debugPrint('❌ 网络连接检查错误: $e');
      // 🔧 Android 15 优化：出错时返回 true，避免误判
      return true;
    }
  }

  /// 监听网络状态变化
  static Stream<ConnectivityResult> kr_networkStream() {
    return Connectivity().onConnectivityChanged;
  }

  /// 打开应用设置页面
  static Future<void> kr_openAppSettings() async {
    if (Platform.isIOS) {
      // iOS 平台打开网络设置
      try {
        await openAppSettings();
      } catch (e) {
        debugPrint('打开设置页面错误: $e');
      }
    } else {
      await openAppSettings();
    }
  }

  /// 显示网络权限对话框
  static Future<bool> kr_showNetworkDialog() async {
    bool? result;
    await KRDialog.show(
      title: Platform.isIOS 
          ? AppTranslations.kr_networkPermission.title 
          : AppTranslations.kr_networkPermission.title,
      message: Platform.isIOS 
          ? AppTranslations.kr_networkPermission.description 
          : AppTranslations.kr_networkPermission.description,
      confirmText: AppTranslations.kr_networkPermission.goToSettings,
      cancelText: AppTranslations.kr_networkPermission.cancel,
      onConfirm: () async {
        result = await openAppSettings();
      },
      onCancel: () {
        result = false;
      },
    );
    return result ?? false;
  }
} 