import 'dart:async';
import 'dart:io';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
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';
import 'package:permission_handler/permission_handler.dart';

class LiveCarePermissionService {
  LiveCarePermissionService._();

  static final LiveCarePermissionService instance = LiveCarePermissionService._();

  // Guard to prevent concurrent permission requests
  Completer<Map<Permission, PermissionStatus>>? _ongoingRequest;

  /// Requests camera, microphone and notification permissions together and
  /// returns the final map of permission statuses.
  /// This method does NOT show any dialogs — UI decisions must be done by caller.
  Future<Map<Permission, PermissionStatus>> requestCameraMicAndNotification(bool isCheckCameraMicPermissions, BuildContext context) async {
    if (_ongoingRequest != null) {
      return _ongoingRequest!.future;
    }

    _ongoingRequest = Completer<Map<Permission, PermissionStatus>>();
    final completer = _ongoingRequest!;

    final permissions = isCheckCameraMicPermissions
        ? <Permission>[
            Permission.camera,
      Permission.microphone,
            Permission.notification,
            // if (Platform.isAndroid) Permission.systemAlertWindow,
          ]
        : <Permission>[
            // Permission.camera,
            // Permission.microphone,
            Permission.notification,
            // if (Platform.isAndroid) Permission.systemAlertWindow,
          ];

    try {
      final statuses = await permissions.request();

      // Ensure all requested keys exist in the returned map (some platforms may omit)
      final result = <Permission, PermissionStatus>{};
      for (final p in permissions) {
        result[p] = statuses[p] ?? await p.status;
      }

      if (!completer.isCompleted) completer.complete(result);
      return completer.future;
    } catch (e) {
      if (!completer.isCompleted) completer.complete(<Permission, PermissionStatus>{});
      return completer.future;
    } finally {
      _ongoingRequest = null;
    }
  }

  /// Show an "open settings" dialog (kept as helper for the UI layer).
  Future<void> showOpenSettingsDialog(BuildContext context, {required String title, required String message}) async {
    return showCommonBottomSheetWithoutHeight(
      title: title,
      context,
      child: Utils.getWarningWidget(
          loadingText: message,
          isShowActionButtons: true,
          onCancelTap: () {
            Navigator.of(context).pop();
          },
          onConfirmTap: () async {
            openAppSettings();
            Navigator.of(context).pop();
          }),
      isFullScreen: false,
      isCloseButtonVisible: true,
      callBackFunc: () {},
    );
    // return showDialog<void>(
    //   context: context,
    //   builder: (c) => ConfirmDialog(
    //     title: '$title Permission',
    //     message: message,
    //     onTap: () {
    //       openAppSettings();
    //       Navigator.of(c).pop();
    //     },
    //     okTitle: LocaleKeys.ok.tr(context: c),
    //   ),
    // );
  }

  String friendlyName(Permission permission) {
    if (permission == Permission.camera) return 'Camera';
    if (permission == Permission.microphone) return 'Microphone';
    if (permission == Permission.notification) return 'Notifications';
    if (permission == Permission.systemAlertWindow) return 'Display over other apps';
    return permission.toString();
  }
}
