import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:geolocator/geolocator.dart' as geo;
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';

class PermissionService {
  // final LocalStorage storage = new LocalStorage("permission");
  geo.LocationPermission? locationPermission;

  // AppGlobal appGlobal = new AppGlobal();

  // setVibrationPermission(flag) async {
  //   storage.setItem('isVibration', flag);
  // }
  //
  // isVibrationEnabled() {
  //   return (storage.getItem('isVibration') == null) ||
  //           (storage.getItem('isVibration')) == false
  //       ? false
  //       : true;
  // }

  // vibrate(callback, context) async {
  //   if (callback == null) return null;
  //   if (isVibrationEnabled() == true) {
  //     // if (await Vibration.hasVibrator() !=null) {
  //     //   Vibration.vibrate(duration: 100);
  //     //   callback();
  //     // }
  //   } else {
  //     callback();
  //   }
  // }

  // setTheme(flag) async {
  //   storage.setItem('isTheme', flag);
  // }
  //
  // isThemeEnabled() {
  //   return storage.getItem('isTheme');
  // }

  cameraPermission() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.camera,
    ].request();
  }

  static isCameraEnabled() async {
    return await Permission.camera.isGranted;
  }

  static isExternalStorageEnabled() async {
    return await Permission.storage.isGranted;
  }

  static isHealthDataPermissionEnabled() async {
    return await Permission.sensors.isGranted;
  }

  static isMicrophonePermissionEnabled() async {
    return await Permission.microphone.isGranted;
  }

  static isCalendarPermissionEnabled() async {
    return await Permission.calendarFullAccess.isGranted;
  }

  setCameraLocationPermission(context) async {
    Navigator.pop(context);
    openAppSettings();
  }

  /// Check and request camera permission with proper dialog handling
  /// Returns true if permission is granted, false otherwise
  Future<bool> checkCameraPermission(BuildContext context) async {
    try {
      print('=== Checking camera permission ===');

      // First check current status
      PermissionStatus currentStatus = await Permission.camera.status;
      print('Current camera permission status: $currentStatus');

      // If already granted, return true
      if (currentStatus.isGranted) {
        print('✅ Camera permission already granted');
        return true;
      }

      // If denied or permanently denied, show settings dialog
      if (currentStatus.isDenied || currentStatus.isPermanentlyDenied) {
        // Request permission first
        PermissionStatus newStatus = await Permission.camera.request();
        print('Camera permission after request: $newStatus');

        if (newStatus.isGranted) {
          print('✅ Camera permission granted');
          return true;
        }

        // Still denied - show settings dialog
        print('⚠️ Camera permission denied - showing settings dialog');
        if (context.mounted) {
          showCommonBottomSheetWithoutHeight(
            title: LocaleKeys.notice.tr(context: context),
            context,
            child: Utils.getWarningWidget(
              loadingText: LocaleKeys.cameraPermissionMessage.tr(context: context),
              isShowActionButtons: true,
              onCancelTap: () {
                Navigator.pop(context);
              },
              onConfirmTap: () async {
                openAppSettings();
              },
            ),
            callBackFunc: () {},
            isFullScreen: false,
            isCloseButtonVisible: true,
          );
        }
        return false;
      }

      // Request permission for the first time
      PermissionStatus newStatus = await Permission.camera.request();
      print('Camera permission after request: $newStatus');

      if (newStatus.isGranted) {
        print('✅ Camera permission granted');
        return true;
      }

      // Denied - show settings dialog
      print('❌ Camera permission denied - showing settings dialog');
      if (context.mounted) {
        showCommonBottomSheetWithoutHeight(
          title: LocaleKeys.notice.tr(context: context),
          context,
          child: Utils.getWarningWidget(
            loadingText: LocaleKeys.cameraPermissionMessage.tr(context: context),
            isShowActionButtons: true,
            onCancelTap: () {
              Navigator.pop(context);
            },
            onConfirmTap: () async {
              openAppSettings();
            },
          ),
          callBackFunc: () {},
          isFullScreen: false,
          isCloseButtonVisible: true,
        );
      }
      return false;
    } catch (e) {
      print('❌ Error checking camera permission: $e');
      if (context.mounted) {
        Utils.showToast(
          LocaleKeys.failedToCheckPermissions.tr(context: context),
        );
      }
      return false;
    }
  }

  /// Check and request gallery/photos permission with proper dialog handling
  /// Returns true if permission is granted, false otherwise
  Future<bool> checkGalleryPermission(BuildContext context) async {
    try {
      print('=== Checking gallery permission ===');

      // For Android 13+ (API 33+), the Android Photo Picker handles permissions internally
      // No need to request READ_MEDIA_IMAGES or READ_EXTERNAL_STORAGE permissions
      // Determine which permission to check based on platform and Android version
      Permission galleryPermission;

      if (Platform.isIOS) {
        galleryPermission = Permission.photos;
      } else {
        // Android: use photos permission which handles API level differences automatically
        print('✅ Android Photo Picker will handle permissions internally');
        return true;
      }

      // First check current status
      PermissionStatus currentStatus = await galleryPermission.status;
      print('Current gallery permission status: $currentStatus');

      // If already granted, return true
      if (currentStatus.isGranted || currentStatus.isLimited) {
        print('✅ Gallery permission already granted');
        return true;
      }

      // If denied or permanently denied, request permission first
      if (currentStatus.isDenied || currentStatus.isPermanentlyDenied) {
        // Request permission first
        PermissionStatus newStatus = await galleryPermission.request();
        print('Gallery permission after request: $newStatus');

        if (newStatus.isGranted || newStatus.isLimited) {
          print('✅ Gallery permission granted');
          return true;
        }

        // Still denied - show settings dialog
        print('⚠️ Gallery permission denied - showing settings dialog');
        if (context.mounted) {
          showCommonBottomSheetWithoutHeight(
            title: LocaleKeys.notice.tr(context: context),
            context,
            child: Utils.getWarningWidget(
              loadingText: LocaleKeys.galleryPermissionMessage.tr(context: context),
              isShowActionButtons: true,
              onCancelTap: () {
                Navigator.pop(context);
              },
              onConfirmTap: () async {
                Navigator.pop(context);
                openAppSettings();
              },
            ),
            callBackFunc: () {},
            isFullScreen: false,
            isCloseButtonVisible: true,
          );
        }
        return false;
      }

      // Request permission for the first time
      PermissionStatus newStatus = await galleryPermission.request();
      print('Gallery permission after request: $newStatus');

      if (newStatus.isGranted || newStatus.isLimited) {
        print('✅ Gallery permission granted');
        return true;
      }

      // Denied - show settings dialog
      print('❌ Gallery permission denied - showing settings dialog');
      if (context.mounted) {
        showCommonBottomSheetWithoutHeight(
          title: LocaleKeys.notice.tr(context: context),
          context,
          child: Utils.getWarningWidget(
            loadingText: LocaleKeys.galleryPermissionMessage.tr(context: context),
            isShowActionButtons: true,
            onCancelTap: () {
              Navigator.pop(context);
            },
            onConfirmTap: () async {
              openAppSettings();
            },
          ),
          callBackFunc: () {},
          isFullScreen: false,
          isCloseButtonVisible: true,
        );
      }
      return false;
    } catch (e) {
      print('❌ Error checking gallery permission: $e');
      if (context.mounted) {
        Utils.showToast(
          LocaleKeys.failedToCheckPermissions.tr(context: context),
        );
      }
      return false;
    }
  }

  static isLocationEnabled() async {
    var permission = await geo.Geolocator.checkPermission();
    if (permission == geo.LocationPermission.denied) {
      return false;
    } else {
      return true;
    }
  }

  openSettings() async {
    openAppSettings();
  }

  openAccessbility() {
    // OpenSettings.openAppSetting();
  }
}
