import 'package:permission_handler/permission_handler.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'dart:io';

import 'log/logger.dart';

class PermissionManager {
  /// 检查是否需要请求存储权限
  static Future<bool> _needsStoragePermission() async {
    if (!Platform.isAndroid) return false;

    try {
      final androidInfo = await DeviceInfoPlugin().androidInfo;
      // Android 10 是 API 29，所以 API 28 及以下是 Android 9 及以下
      return androidInfo.version.sdkInt <= 29;
    } catch (e) {
      log('PermissionManager', 'Error checking Android version: $e');
      return false;
    }
  }

  /// 请求存储权限
  static Future<bool> requestStoragePermission() async {
    // 检查是否需要请求权限
    if (!await _needsStoragePermission()) {
      return true;
    }

    try {
      var status = await Permission.storage.status;

      if (status.isGranted) {
        return true;
      }

      if (status.isPermanentlyDenied) {
        // await openAppSettings();
        return false;
      }

      status = await Permission.storage.request();
      return status.isGranted;
    } catch (e) {
      log('PermissionManager', 'Error requesting storage permission: $e');
      return false;
    }
  }

  /// 检查存储权限
  static Future<bool> checkStoragePermission() async {
    // 检查是否需要请求权限
    if (!await _needsStoragePermission()) {
      return true;
    }

    try {
      final status = await Permission.storage.status;
      return status.isGranted;
    } catch (e) {
      log('PermissionManager', 'Error checking storage permission: $e');
      return false;
    }
  }

  // ============== 通知权限管理 ==============

  /// 检查通知权限状态
  static Future<PermissionStatus> checkNotificationPermission() async {
    try {
      return await Permission.notification.status;
    } catch (e) {
      log('PermissionManager', 'Error checking notification permission: $e');
      return PermissionStatus.denied;
    }
  }

  /// 检查通知权限是否已授予
  static Future<bool> isNotificationPermissionGranted() async {
    try {
      final status = await Permission.notification.status;
      return status.isGranted;
    } catch (e) {
      log('PermissionManager', 'Error checking notification permission: $e');
      return false;
    }
  }

  /// 请求通知权限
  /// 返回 true 表示已授予权限，false 表示被拒绝
  static Future<bool> requestNotificationPermission() async {
    try {
      var status = await Permission.notification.status;

      // 如果已经授予，直接返回
      if (status.isGranted) {
        log('PermissionManager', 'Notification permission already granted');
        return true;
      }

      // 如果被永久拒绝，引导用户到设置页面
      if (status.isPermanentlyDenied) {
        log(
          'PermissionManager',
          'Notification permission permanently denied, opening settings',
        );
        await openAppSettings();
        return false;
      }

      // 请求权限
      log('PermissionManager', 'Requesting notification permission');
      status = await Permission.notification.request();

      final granted = status.isGranted;
      log(
        'PermissionManager',
        'Notification permission request result: $granted',
      );

      return granted;
    } catch (e) {
      log('PermissionManager', 'Error requesting notification permission: $e');
      return false;
    }
  }

  /// 检查通知权限是否被永久拒绝
  static Future<bool> isNotificationPermissionPermanentlyDenied() async {
    try {
      final status = await Permission.notification.status;
      return status.isPermanentlyDenied;
    } catch (e) {
      log('PermissionManager', 'Error checking notification permission: $e');
      return false;
    }
  }

  /// 打开应用设置页面
  static Future<bool> openNotificationSettings() async {
    try {
      log(
        'PermissionManager',
        'Opening app settings for notification permission',
      );
      return await openAppSettings();
    } catch (e) {
      log('PermissionManager', 'Error opening app settings: $e');
      return false;
    }
  }

  /// 获取通知权限的详细状态
  static Future<NotificationPermissionInfo>
  getNotificationPermissionInfo() async {
    try {
      final status = await Permission.notification.status;

      return NotificationPermissionInfo(
        isGranted: status.isGranted,
        isDenied: status.isDenied,
        isPermanentlyDenied: status.isPermanentlyDenied,
        isRestricted: status.isRestricted,
        isLimited: status.isLimited,
        canRequest: !status.isPermanentlyDenied && !status.isGranted,
      );
    } catch (e) {
      log(
        'PermissionManager',
        'Error getting notification permission info: $e',
      );
      return NotificationPermissionInfo(
        isGranted: false,
        isDenied: true,
        isPermanentlyDenied: false,
        isRestricted: false,
        isLimited: false,
        canRequest: true,
      );
    }
  }
}

/// 通知权限信息类
class NotificationPermissionInfo {
  /// 是否已授予
  final bool isGranted;

  /// 是否被拒绝
  final bool isDenied;

  /// 是否被永久拒绝
  final bool isPermanentlyDenied;

  /// 是否受限制（iOS）
  final bool isRestricted;

  /// 是否为有限权限（iOS）
  final bool isLimited;

  /// 是否可以请求
  final bool canRequest;

  NotificationPermissionInfo({
    required this.isGranted,
    required this.isDenied,
    required this.isPermanentlyDenied,
    required this.isRestricted,
    required this.isLimited,
    required this.canRequest,
  });

  @override
  String toString() {
    return 'NotificationPermissionInfo(isGranted: $isGranted, isDenied: $isDenied, '
        'isPermanentlyDenied: $isPermanentlyDenied, isRestricted: $isRestricted, '
        'isLimited: $isLimited, canRequest: $canRequest)';
  }
}
