import 'dart:io' show Platform;

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_export.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/calender_utils_new.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/prescriptions/prescription_reminder_view.dart';
import 'package:hmg_patient_app_new/services/navigation_service.dart';
import 'package:hmg_patient_app_new/services/permission_service.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:permission_handler/permission_handler.dart';

class BottomSheetUtils {
  Future<bool> showReminderBottomSheet(BuildContext context, DateTime dateTime, String doctorName, String eventId, String appoDateFormatted, String appoTimeFormatted,
      {required Function() onSuccess, String? title, String? description, Function(int)? onMultiDateSuccess, bool isMultiAllowed = false, bool isForAppointment = false}) async {
    // Check and request permissions based on platform
    bool hasPermission = await _checkAndRequestCalendarPermissions();

    if (hasPermission) {
      // Permission granted, show the reminder selection bottom sheet
      await _showReminderBottomSheet(context, dateTime, doctorName, eventId, appoDateFormatted, appoTimeFormatted,
          onSuccess: onSuccess, title: title, description: description, onMultiDateSuccess: onMultiDateSuccess, isMultiAllowed: isMultiAllowed);
      return true;
    } else {
      await _showPermissionDeniedDialog(isForAppointment: isForAppointment);
      return false;
    }
  }

  /// Checks and requests calendar permissions for both Android and iOS
  /// Returns true if all required permissions are granted
  Future<bool> _checkAndRequestCalendarPermissions() async {
    if (Platform.isAndroid) {
      // Android: Check existing permission first using PermissionService
      bool hasPermission = await PermissionService.isCalendarPermissionEnabled();
      if (hasPermission) {
        return true;
      }

      // Request calendarFullAccess permission (Android 14+ requires this)
      // This internally requests both READ_CALENDAR and WRITE_CALENDAR
      PermissionStatus status = await Permission.calendarFullAccess.request();

      // If calendarFullAccess request didn't show dialog or failed,
      // fallback to requesting individual permissions
      if (!status.isGranted) {
        Map<Permission, PermissionStatus> statuses = await [
          Permission.calendarWriteOnly,
        ].request();

        return statuses[Permission.calendarWriteOnly]?.isGranted ?? false;
      }

      return status.isGranted;
    } else {
      // iOS: Check if we already have full access
      PermissionStatus fullAccessStatus = await Permission.calendarFullAccess.status;

      if (fullAccessStatus.isGranted) {
        return true;
      }

      // Request write permission first (required before full access on iOS)
      PermissionStatus writeStatus = await Permission.calendarWriteOnly.request();
      if (!writeStatus.isGranted) {
        return false;
      }

      // Then request full access permission
      PermissionStatus fullStatus = await Permission.calendarFullAccess.request();
      return fullStatus.isGranted;
    }
  }

  /// Shows permission denied dialog with option to open settings
  Future<void> _showPermissionDeniedDialog({bool isForAppointment = false}) async {
    BuildContext? context = GetIt.instance<NavigationService>().navigatorKey.currentContext;
    if (context == null) return;

    showCommonBottomSheetWithoutHeight(
      context,
      title: LocaleKeys.notice.tr(context: context),
      child: Utils.getWarningWidget(
        loadingText: isForAppointment ? LocaleKeys.calendarPermissionAlertForAppointment.tr() : LocaleKeys.calendarPermissionAlert.tr(),
        isShowActionButtons: true,
        onCancelTap: () {
          GetIt.instance<NavigationService>().pop();
        },
        onConfirmTap: () async {
          GetIt.instance<NavigationService>().pop();
          await openAppSettings();
        },
      ),
      callBackFunc: () {},
      isFullScreen: false,
      isCloseButtonVisible: true,
    );
  }

  Future<void> _showReminderBottomSheet(BuildContext providedContext, DateTime dateTime, String doctorName, String eventId, String appoDateFormatted, String appoTimeFormatted,
      {required Function onSuccess, String? title, String? description, Function(int)? onMultiDateSuccess, bool? isMultiAllowed}) async {
    showCommonBottomSheetWithoutHeight(providedContext, title: LocaleKeys.setTimerOfReminder.tr(context: providedContext), child: PrescriptionReminderView(
      setReminder: (int value) async {
        if (!isMultiAllowed!) {
          if (onMultiDateSuccess == null) {
            CalenderUtilsNew calendarUtils = CalenderUtilsNew.instance;
            await calendarUtils.createOrUpdateEvent(
                title: title ?? LocaleKeys.youHaveAppointmentWithDr.tr(context: providedContext) + doctorName,
                description: description ?? "At " + appoDateFormatted + " " + appoTimeFormatted,
                scheduleDateTime: dateTime,
                eventId: eventId,
                location: '');
            onSuccess();
          }
        } else {
          onMultiDateSuccess!(value);
        }
      },
    ), callBackFunc: () {}, isFullScreen: false);
  }
}

void showCommonBottomSheet(BuildContext context,
    {required Widget child,
    Function(String?)? callBackFunc,
    String? title,
    required double height,
    bool isAutoDismiss = false,
    bool isCloseButtonVisible = true,
    bool isFullScreen = true,
    bool isDismissible = true,
    bool isSuccessDialog = false}) {
  showModalBottomSheet<String>(
      sheetAnimationStyle: AnimationStyle(
        duration: Duration(milliseconds: 500), // Custom animation duration
        reverseDuration: Duration(milliseconds: 300), // Custom reverse animation duration
      ),
      context: context,
      isScrollControlled: true,
      showDragHandle: false,
      isDismissible: isDismissible,
      backgroundColor: isSuccessDialog ? AppColors.whiteColor : AppColors.scaffoldBgColor,
      builder: (BuildContext context) {
        if (isAutoDismiss) {
          Future.delayed(Duration(seconds: 2), () {
            final navContext = getIt.get<NavigationService>().navigatorKey.currentContext;
            if (navContext != null && Navigator.canPop(navContext)) {
              Navigator.of(navContext).pop();
            }
            if (callBackFunc != null) {
              callBackFunc(null);
            }
          });
        }
        return Container(
          height: height,
          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.scaffoldBgColor, borderRadius: 24.h),
          child: ButtonSheetContent(
            title: title!,
            isCloseButtonVisible: isCloseButtonVisible,
            isFullScreen: isFullScreen,
            child: child,
          ),
        );
      }).then((value) {
    if (value != null) {
      callBackFunc!(value);
    }
  });
}

class ButtonSheetContent extends StatelessWidget {
  final Widget child;
  final String title;
  final bool isCloseButtonVisible;
  final bool isFullScreen;

  const ButtonSheetContent({super.key, required this.child, required this.isCloseButtonVisible, required this.title, required this.isFullScreen});

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          height: 20.h,
        ),
        // Center(
        //   child: Container(
        //     margin: const EdgeInsets.only(top: 18, bottom: 12),
        //     height: 4,
        //     width: 40.h,
        //     decoration: BoxDecoration(
        //       color: Colors.grey[400],
        //       borderRadius: BorderRadius.circular(2),
        //     ),
        //   ),
        // ),

        // Close button
        isCloseButtonVisible && isFullScreen
            ? Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                Padding(
                  padding: EdgeInsets.symmetric(
                    horizontal: 16,
                  ),
                  child: Utils.buildSvgWithAssets(icon: AppAssets.closeBottomNav, width: 32, height: 32, applyThemeColor: false).onPress(() {
                    Navigator.of(context).pop();
                  }),
                )
              ])
            : SizedBox(),

        isFullScreen
            ? Column(
                children: [
                  // SizedBox(height: 20.h),
                  Padding(padding: EdgeInsets.symmetric(horizontal: 16.h), child: title.toText24(isBold: true)),
                  SizedBox(height: 16.h),
                ],
              )
            : SizedBox(),

        Expanded(child: child)
      ],
    );
  }
}

void showCommonBottomSheetWithoutHeight(
  BuildContext context, {
  required Widget child,
  VoidCallback? callBackFunc,
  String title = "",
  bool isConfirmButton = false,
  bool isCloseButtonVisible = true,
  bool isFullScreen = true,
  bool isDismissible = true,
  bool isAutoDismiss = false,
  Widget? titleWidget,
  bool useSafeArea = false,
  bool hasBottomPadding = true,
  EdgeInsets? padding,
  Color? backgroundColor,
  VoidCallback? onCloseClicked,
}) {
  final resolvedBgColor = backgroundColor ?? AppColors.bottomSheetBgColor;
  showModalBottomSheet<String>(
    sheetAnimationStyle: AnimationStyle(
      duration: Duration(milliseconds: 500),
      reverseDuration: Duration(milliseconds: 300),
    ),
    constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width),
    context: context,
    isScrollControlled: true,
    showDragHandle: false,
    isDismissible: isDismissible,
    enableDrag: isDismissible,
    backgroundColor: resolvedBgColor,
    useSafeArea: useSafeArea,
    builder: (BuildContext context) {
      if (isAutoDismiss) {
        Future.delayed(Duration(seconds: 2), () {
          final navContext = GetIt.instance<NavigationService>().navigatorKey.currentContext;
          if (navContext != null && Navigator.canPop(navContext)) {
            Navigator.of(navContext).pop();
          }
          // if (callBackFunc != null) {
          //   callBackFunc();
          // }
        });
      }
      return SafeArea(
        top: false,
        left: false,
        right: false,
        bottom: hasBottomPadding,
        child: Padding(
          padding: EdgeInsets.only(
            bottom: MediaQuery.of(context).viewInsets.bottom,
          ),
          child: SingleChildScrollView(
            physics: ClampingScrollPhysics(),
            child: isCloseButtonVisible
                ? Container(
                    padding: padding ??
                        const EdgeInsets.only(
                          left: 24,
                          top: 24,
                          right: 24,
                          bottom: 12,
                        ),
                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                      color: AppColors.bottomSheetBgColor,
                      borderRadius: 24.h,
                    ),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Padding(
                          padding: padding != null ? EdgeInsets.symmetric(horizontal: 24.w) : EdgeInsets.zero,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              titleWidget ??
                                  Expanded(
                                    child: title.toText20(isBold: true),
                                  ),
                              if (isCloseButtonVisible) ...[
                                Utils.buildSvgWithAssets(
                                  icon: AppAssets.close_bottom_sheet_icon,
                                  iconColor: AppColors.textColor,
                                ).onPress(() {
                                  onCloseClicked?.call();
                                  Navigator.of(context).pop();
                                }),
                              ],
                            ],
                          ),
                        ),
                        isCloseButtonVisible ? SizedBox(height: 16.h) : SizedBox.shrink(),
                        child,
                      ],
                    ),
                  )
                : child,
          ),
        ),
      );
    },
  ).then((value) {
    if (callBackFunc != null) {
      callBackFunc();
    }
  });
}

// void showCommonBottomSheetWithoutHeight(
//   BuildContext context, {
//   required Widget child,
//   required VoidCallback callBackFunc,
//   String title = "",
//   bool isCloseButtonVisible = true,
//   bool isFullScreen = true,
//   bool isDismissible = true,
//   Widget? titleWidget,
//   bool useSafeArea = false,
//
// }) {
//   showModalBottomSheet<String>(
//       sheetAnimationStyle: AnimationStyle(
//         duration: Duration(milliseconds: 500), // Custom animation duration
//         reverseDuration: Duration(milliseconds: 300), // Custom reverse animation duration
//       ),
//       context: context,
//       isScrollControlled: true,
//       showDragHandle: false,
//       isDismissible: isDismissible,
//       backgroundColor: AppColors.bottomSheetBgColor,
//       useSafeArea: useSafeArea,
//       builder: (BuildContext context) {
//         return SafeArea(
//           top: false,
//           left: false,
//           right: false,
//           child: isCloseButtonVisible
//               ? Container(
//                   padding: EdgeInsets.only(left: 24, top: 24, right: 24, bottom: 12),
//                   decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.bottomSheetBgColor, borderRadius: 24.h),
//                   child: Column(
//                     mainAxisSize: MainAxisSize.min,
//                     spacing: 16.h,
//                     children: [
//                       Row(
//                         mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                         crossAxisAlignment: CrossAxisAlignment.center,
//                         children: [
//                           titleWidget ?? Expanded(child: title.toText20(isBold: true)),
//                           Utils.buildSvgWithAssets(icon: AppAssets.close_bottom_sheet_icon, iconColor: Color(0xff2B353E)).onPress(() {
//                             Navigator.of(context).pop();
//                           }),
//                         ],
//                       ),
//                       child,
//                     ],
//                   ))
//               : child,
//         );
//       }).then((value) {
//     callBackFunc();
//   });
// }
