import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/int_extensions.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/features/book_appointments/book_appointments_view_model.dart';
import 'package:hmg_patient_app_new/features/immediate_livecare/immediate_livecare_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/immediate_livecare_payment_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/immediate_livecare_pending_request_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/livecare/widgets/select_livecare_call_type.dart';
import 'package:hmg_patient_app_new/presentation/home/navigation_screen.dart';
import 'package:hmg_patient_app_new/presentation/insurance/insurance_home_page.dart';
import 'package:hmg_patient_app_new/services/livecare_permission_service.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:smooth_corner/smooth_corner.dart';

class ImmediateLiveCarePaymentDetails extends StatelessWidget {
  ImmediateLiveCarePaymentDetails({super.key});

  // late ImmediateLiveCareViewModel immediateLiveCareViewModel;
  late AppState appState;

  @override
  Widget build(BuildContext context) {
    // immediateLiveCareViewModel = Provider.of<ImmediateLiveCareViewModel>(context, listen: false);
    appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.scaffoldBgColor,
      body: Consumer<ImmediateLiveCareViewModel>(builder: (context, immediateLiveCareVM, child) {
        return Column(
          children: [
            Expanded(
              child: CollapsingListView(
                title: LocaleKeys.reviewLiveCareRequest.tr(context: context),
                child: SingleChildScrollView(
                  padding: EdgeInsets.symmetric(horizontal: 24.h),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(height: 24.h),
                      LocaleKeys.patientInfo.tr(context: context).toText16(isBold: true),
                      SizedBox(height: 16.h),
                      Container(
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                          color: AppColors.whiteColor,
                          borderRadius: 24.h,
                          hasShadow: false,
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(16.h),
                          child: Row(
                            children: [
                              Utils.buildImgWithAssets(
                                icon: appState.getAuthenticatedUser()?.gender == 1 ? AppAssets.maleImg : AppAssets.femaleImg,
                                width: 52.h,
                                height: 52.h,
                              ),
                              SizedBox(width: 8.h),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}"
                                      .toText16(isBold: true, isEnglishOnly: true),
                                  SizedBox(height: 8.h),
                                  Wrap(
                                    direction: Axis.horizontal,
                                    spacing: 3.h,
                                    runSpacing: 4.h,
                                    children: [
                                      AppCustomChipWidget(
                                        richText: Row(
                                          children: [
                                            "${appState.getAuthenticatedUser()!.age} ".toText10(color: AppColors.blackColor, isBold: true),
                                            LocaleKeys.yearsOld.tr(context: context).toText10(color: AppColors.blackColor, isBold: true),
                                          ],
                                        ),
                                      ),
                                      AppCustomChipWidget(
                                          labelText:
                                              "${LocaleKeys.gender.tr(context: context)}: ${appState.getAuthenticatedUser()?.gender == 1 ? LocaleKeys.malE.tr(context: context) : LocaleKeys.femaleGender.tr(context: context)}"),
                                    ],
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(height: 24.h),
                      LocaleKeys.selectedLiveCareType.tr(context: context).toText16(isBold: true),
                      SizedBox(height: 16.h),
                      Consumer<BookAppointmentsViewModel>(builder: (context, bookAppointmentsVM, child) {
                        return Container(
                          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                            color: AppColors.whiteColor,
                            borderRadius: 24.h,
                            hasShadow: false,
                          ),
                          child: Padding(
                            padding: EdgeInsets.all(16.h),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                AppCustomChipWidget(
                                    labelText:
                                        "${LocaleKeys.clinic.tr()}: ${(appState.isArabic() ? immediateLiveCareVM.immediateLiveCareSelectedClinic.serviceNameN : immediateLiveCareVM.immediateLiveCareSelectedClinic.serviceName) ?? ""}"),
                                SizedBox(height: 16.h),
                                1.divider,
                                SizedBox(height: 16.h),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      children: [
                                        Utils.buildSvgWithAssets(
                                            icon: getLiveCareTypeIcon(immediateLiveCareVM.liveCareSelectedCallType),
                                            width: 32.h,
                                            height: 32.h,
                                            fit: BoxFit.contain,
                                            applyThemeColor: false),
                                        SizedBox(width: 8.h),
                                        getLiveCareType(context, immediateLiveCareVM.liveCareSelectedCallType).toText16(isBold: true),
                                      ],
                                    ),
                                    Utils.buildSvgWithAssets(icon: AppAssets.edit_icon, width: 24.h, height: 24.h, fit: BoxFit.contain),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ).onPress(() {
                          showCommonBottomSheetWithoutHeight(context, child: SelectLiveCareCallType(immediateLiveCareViewModel: immediateLiveCareVM),
                              callBackFunc: () async {
                            debugPrint("Selected Call Type: ${immediateLiveCareVM.liveCareSelectedCallType}");
                          }, title: LocaleKeys.selectLiveCareCallType.tr(context: context), isCloseButtonVisible: true, isFullScreen: false);
                        });
                      }),
                      SizedBox(height: 24.h)
                    ],
                  ),
                ),
              ),
            ),
            Container(
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.whiteColor,
                borderRadius: 24.h,
                hasShadow: false,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  (immediateLiveCareVM.liveCareImmediateAppointmentFeesList.isCash ?? true)
                      ? Container(
                          height: 50.h,
                          decoration: ShapeDecoration(
                            color: AppColors.secondaryLightRedBorderColor,
                            shape: SmoothRectangleBorder(
                              borderRadius: BorderRadius.only(topLeft: Radius.circular(24), topRight: Radius.circular(24)),
                              smoothness: 1,
                            ),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              LocaleKeys.insuranceExpiredOrInactive
                                  .tr(context: context)
                                  .toText14(color: AppColors.primaryRedColor, isBold: true)
                                  .paddingSymmetrical(24.h, 0.h),
                              CustomButton(
                                text: LocaleKeys.updateInsurance.tr(context: context),
                                onPressed: () {
                                  showCommonBottomSheetWithoutHeight(
                                    title: LocaleKeys.notice.tr(context: context),
                                    context,
                                    child: Utils.getWarningWidget(
                                        loadingText: LocaleKeys.livecareUpdateInsurance.tr(),
                                        isShowActionButtons: true,
                                        onCancelTap: () {
                                          Navigator.pop(context);
                                        },
                                        onConfirmTap: () async {
                                          Navigator.pop(context);
                                          LoaderBottomSheet.showLoader(loadingText: LocaleKeys.loadingText.tr());
                                          await immediateLiveCareVM.addInsuranceUpdateRequestForLiveCare(onSuccess: (val) {
                                            LoaderBottomSheet.hideLoader();
                                            showCommonBottomSheetWithoutHeight(
                                              context,
                                              child: Utils.getSuccessWidget(loadingText: LocaleKeys.livecareUpdateInsuranceSent.tr()),
                                              callBackFunc: () {},
                                              isFullScreen: false,
                                              isCloseButtonVisible: true,
                                            );
                                          }, onError: (err) {
                                            LoaderBottomSheet.hideLoader();
                                            showCommonBottomSheetWithoutHeight(
                                              context,
                                              child: Utils.getErrorWidget(loadingText: err),
                                              callBackFunc: () {},
                                              isFullScreen: false,
                                              isCloseButtonVisible: true,
                                            );
                                          });
                                        }),
                                    callBackFunc: () {},
                                    isFullScreen: false,
                                    isCloseButtonVisible: true,
                                  );

                                  // Navigator.of(context)
                                  //     .push(
                                  //   CustomPageRoute(
                                  //     page: InsuranceHomePage(),
                                  //   ),
                                  // )
                                  //     .then((val) async {
                                  //   LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingFeesPleaseWait.tr());
                                  //   await immediateLiveCareVM.getLiveCareImmediateAppointmentFees(onSuccess: (val) {
                                  //     LoaderBottomSheet.hideLoader();
                                  //   }, onError: (err) {
                                  //     LoaderBottomSheet.hideLoader();
                                  //     showCommonBottomSheetWithoutHeight(
                                  //       context,
                                  //       child: Utils.getErrorWidget(loadingText: err),
                                  //       callBackFunc: () {},
                                  //       isFullScreen: false,
                                  //       isCloseButtonVisible: true,
                                  //     );
                                  //   });
                                  // });
                                },
                                backgroundColor: AppColors.primaryRedColor,
                                borderColor: AppColors.secondaryLightRedBorderColor,
                                textColor: AppColors.whiteColor,
                                fontSize: 10,
                                fontWeight: FontWeight.w600,
                                borderRadius: 8,
                                padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
                                height: 30.h,
                              ).paddingSymmetrical(24.h, 0.h),
                            ],
                          ),
                        )
                      : const SizedBox(),
                  SizedBox(height: 24.h),
                  LocaleKeys.totalAmountToPay.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.h, 0.h),
                  SizedBox(height: 17.h),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      LocaleKeys.amountBeforeTax.tr(context: context).toText14(isBold: true),
                      Utils.getPaymentAmountWithSymbol(
                          (immediateLiveCareVM.liveCareImmediateAppointmentFeesList.amount ?? "").toText16(isBold: true, isEnglishOnly: true),
                          AppColors.blackColor,
                          13,
                          isSaudiCurrency: (immediateLiveCareVM.liveCareImmediateAppointmentFeesList.currency ?? "sar").toLowerCase() == "sar" ||
                              (immediateLiveCareVM.liveCareImmediateAppointmentFeesList.currency ?? "ريال").toLowerCase() == "ريال"),
                    ],
                  ).paddingSymmetrical(24.h, 0.h),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      LocaleKeys.vat15.tr(context: context).toText14(isBold: true, color: AppColors.greyTextColor),
                      Utils.getPaymentAmountWithSymbol(
                          (immediateLiveCareVM.liveCareImmediateAppointmentFeesList.tax ?? "0.0")
                              .toText14(isBold: true, color: AppColors.greyTextColor, isEnglishOnly: true),
                          AppColors.greyTextColor,
                          13,
                          isSaudiCurrency: ((immediateLiveCareVM.liveCareImmediateAppointmentFeesList.currency ?? "sar").toLowerCase() == "sar" ||
                              (immediateLiveCareVM.liveCareImmediateAppointmentFeesList.currency ?? "ريال").toLowerCase() == "ريال")),
                    ],
                  ).paddingSymmetrical(24.h, 0.h),
                  SizedBox(height: 17.h),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Utils.getPaymentMethods(),
                      Utils.getPaymentAmountWithSymbol(
                          (immediateLiveCareVM.liveCareImmediateAppointmentFeesList.total ?? "0.0").toText24(isBold: true, isEnglishOnly: true),
                          AppColors.blackColor,
                          17,
                          isSaudiCurrency: ((immediateLiveCareVM.liveCareImmediateAppointmentFeesList.currency ?? "sar").toLowerCase() == "sar" ||
                              (immediateLiveCareVM.liveCareImmediateAppointmentFeesList.currency ?? "ريال").toLowerCase() == "ريال")),
                    ],
                  ).paddingSymmetrical(24.h, 0.h),
                  (immediateLiveCareVM.liveCareImmediateAppointmentFeesList.total == "0" ||
                          immediateLiveCareVM.liveCareImmediateAppointmentFeesList.total == "0.0")
                      // (true)
                      ? CustomButton(
                          text: LocaleKeys.confirmLiveCare.tr(context: context),
                          onPressed: () async {
                            await askVideoCallPermission(context).then((val) async {
                              if (val) {
                                LoaderBottomSheet.showLoader(loadingText: LocaleKeys.confirmingLiveCareRequest.tr(context: context));

                                await immediateLiveCareVM.addNewCallRequestForImmediateLiveCare(
                                    "${appState.getAuthenticatedUser()!.patientId}${DateTime.now().millisecondsSinceEpoch}");
                                await immediateLiveCareVM.getPatientLiveCareHistory();
                                LoaderBottomSheet.hideLoader();
                                if (immediateLiveCareVM.patientHasPendingLiveCareRequest) {
                                  Navigator.pushAndRemoveUntil(
                                      context,
                                      CustomPageRoute(
                                        page: LandingNavigation(),
                                      ),
                                      (r) => false);
                                  Navigator.of(context).push(
                                    CustomPageRoute(
                                      page: ImmediateLiveCarePendingRequestPage(),
                                    ),
                                  );
                                } else {
                                  showCommonBottomSheetWithoutHeight(
                                    context,
                                    child: Utils.getErrorWidget(loadingText: LocaleKeys.unknownErrorOccurred.tr(context: context)),
                                    callBackFunc: () {},
                                    isFullScreen: false,
                                    isCloseButtonVisible: true,
                                  );
                                }
                              } else {
                                showCommonBottomSheetWithoutHeight(
                                  title: LocaleKeys.notice.tr(context: context),
                                  context,
                                  child: Utils.getWarningWidget(
                                      loadingText: LocaleKeys.liveCarePermissionsMessage.tr(context: context),
                                      isShowActionButtons: true,
                                      onCancelTap: () {
                                        Navigator.pop(context);
                                      },
                                      onConfirmTap: () async {
                                        openAppSettings();
                                      }),
                                  callBackFunc: () {},
                                  isFullScreen: false,
                                  isCloseButtonVisible: true,
                                );
                              }
                            });
                          },
                          backgroundColor: AppColors.successColor,
                          borderColor: AppColors.successColor,
                          textColor: AppColors.whiteColor,
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          borderRadius: 12,
                          padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                          height: 50.h,
                          icon: AppAssets.livecare_book_icon,
                          iconColor: AppColors.whiteColor,
                          iconSize: 18.h,
                        ).paddingSymmetrical(24.h, 24.h)
                      : CustomButton(
                          text: LocaleKeys.payNow.tr(context: context),
                          onPressed: () async {
                            await askVideoCallPermission(context).then((val) {
                              if (val) {
                                Navigator.of(context).push(
                                  CustomPageRoute(
                                    page: ImmediateLiveCarePaymentPage(),
                                  ),
                                );
                              }
                              // else {
                              //   showCommonBottomSheetWithoutHeight(
                              //     title: LocaleKeys.notice.tr(context: context),
                              //     context,
                              //     child: Utils.getWarningWidget(
                              //         loadingText: LocaleKeys.liveCarePermissionsMessage.tr(context: context),
                              //               isShowActionButtons: true,
                              //               onCancelTap: () {
                              //                 Navigator.pop(context);
                              //               },
                              //               onConfirmTap: () async {
                              //                 openAppSettings();
                              //               }),
                              //           callBackFunc: () {},
                              //           isFullScreen: false,
                              //     isCloseButtonVisible: true,
                              //   );
                              // }
                            });
                          },
                          backgroundColor: AppColors.infoColor,
                          borderColor: AppColors.infoColor,
                          textColor: AppColors.whiteColor,
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          borderRadius: 12,
                          padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                          height: 50.h,
                          icon: AppAssets.appointment_pay_icon,
                          iconColor: AppColors.whiteColor,
                          iconSize: 18.h,
                        ).paddingSymmetrical(24.h, 24.h),
                ],
              ),
            ),
          ],
        );
      }),
    );
  }

  Future<bool> askVideoCallPermission(BuildContext context) async {
    final statuses = await LiveCarePermissionService.instance.requestCameraMicAndNotification(false, context);

    // If service returned nothing (error), treat as not granted
    if (statuses.isEmpty) return false;

    // bool cameraGranted = statuses[Permission.camera]?.isGranted ?? false;
    // bool micGranted = statuses[Permission.microphone]?.isGranted ?? false;
    bool notifGranted = statuses[Permission.notification]?.isGranted ?? false;
    // bool alertWindowGranted = Platform.isAndroid ? (statuses[Permission.systemAlertWindow]?.isGranted ?? false) : true;
    bool alertWindowGranted = true;

    // If all required permissions are already granted
    // if (cameraGranted && micGranted && notifGranted && alertWindowGranted) return true;
    if (notifGranted && alertWindowGranted) return true;

    // Collect only the missing permissions
    final missing = <Permission>[];
    // if (!cameraGranted) missing.add(Permission.camera);
    // if (!micGranted) missing.add(Permission.microphone);
    if (!notifGranted) missing.add(Permission.notification);
    if (Platform.isAndroid && !alertWindowGranted) missing.add(Permission.systemAlertWindow);

    // If any of the missing permissions are permanently denied/restricted -> open settings (single dialog)
    final permanent = missing.where((p) => (statuses[p]?.isPermanentlyDenied ?? false) || (statuses[p]?.isRestricted ?? false)).toList();
    if (permanent.isNotEmpty) {
      final names = permanent.map((p) => LiveCarePermissionService.instance.friendlyName(p)).join(' and ');
      // final message = permanent.length == 1 ? '$names permission is permanently denied. Open app settings to allow it.' : '$names permissions are permanently denied. Open app settings to allow them.';
      final message = LocaleKeys.liveCareNotificationPermissionsMessage.tr();
      await LiveCarePermissionService.instance.showOpenSettingsDialog(
        context,
        title: LocaleKeys.permissionsProfile.tr(),
        message: message,
      );
      return false;
    }

    // Show one combined retry dialog for all missing permissions
    // final missingNames = missing.map((p) => LiveCarePermissionService.instance.friendlyName(p)).join(' and ');
    // final retry = await showDialog<bool>(
    //   context: context,
    //   builder: (c) => AlertDialog(
    //     title: const Text('Permissions required'),
    //     content: Text('$missingNames permission${missing.length > 1 ? 's are' : ' is'} required to start the video call. Retry now?'),
    //     actions: [
    //       TextButton(onPressed: () => Navigator.of(c).pop(false), child: const Text('Cancel')),
    //       TextButton(onPressed: () => Navigator.of(c).pop(true), child: const Text('Retry')),
    //     ],
    //   ),
    // );
    //
    // if (retry != true) return false;

    // Request only the missing permissions
    final newStatuses = <Permission, PermissionStatus>{};
    for (final p in missing) {
      newStatuses[p] = await p.request();
    }

    // Update grant state (preserve previously granted ones)
    // cameraGranted = newStatuses[Permission.camera]?.isGranted ?? cameraGranted;
    // micGranted = newStatuses[Permission.microphone]?.isGranted ?? micGranted;
    notifGranted = newStatuses[Permission.notification]?.isGranted ?? notifGranted;
    // alertWindowGranted = newStatuses[Permission.systemAlertWindow]?.isGranted ?? alertWindowGranted;
    alertWindowGranted = true;

    // If any requested permission is now permanently denied -> open settings
    final newlyPermanent = missing.where((p) => (newStatuses[p]?.isPermanentlyDenied ?? false) || (newStatuses[p]?.isRestricted ?? false)).toList();
    if (newlyPermanent.isNotEmpty) {
      final names = newlyPermanent.map((p) => LiveCarePermissionService.instance.friendlyName(p)).join(' and ');
      final message = newlyPermanent.length == 1
          ? '$names permission is permanently denied. Open app settings to allow it.'
          : '$names permissions are permanently denied. Open app settings to allow them.';
      await LiveCarePermissionService.instance.showOpenSettingsDialog(
        context,
        title: "Permissions Required",
        message: message,
      );
      return false;
    }

    // return cameraGranted && micGranted && notifGranted && alertWindowGranted;
    // return cameraGranted && micGranted && notifGranted;
    return notifGranted;
  }

  // Future<bool> askVideoCallPermission() async {
  //   bool hasPermission = false;
  //   if (Platform.isIOS) {
  //     Map<Permission, PermissionStatus> statuses = await [Permission.camera, Permission.microphone].request();
  //
  //     if (statuses[Permission.camera] == PermissionStatus.granted && statuses[Permission.microphone] == PermissionStatus.granted) {
  //       // Camera permission granted
  //       hasPermission = true;
  //     } else {
  //       hasPermission = false;
  //     }
  //   } else {
  //     Map<Permission, PermissionStatus> statuses = await [Permission.camera, Permission.microphone, Permission.notification].request();
  //
  //     if (statuses[Permission.camera] == PermissionStatus.granted && statuses[Permission.microphone] == PermissionStatus.granted && statuses[Permission.notification] == PermissionStatus.granted) {
  //       // Camera permission granted
  //       hasPermission = true;
  //     } else {
  //       hasPermission = false;
  //     }
  //   }
  //
  //   return hasPermission;
  //
  //   // if (!(await Permission.camera.request().isGranted) || !(await Permission.microphone.request().isGranted)) {
  //   //   return false;
  //   // }
  // }

  String getLiveCareTypeIcon(int callType) {
    switch (callType) {
      case 1:
        return AppAssets.livecare_video;
      case 2:
        return AppAssets.livecare_audio;
      case 3:
        return AppAssets.livecare_phone;
      default:
        return AppAssets.livecare_video;
    }
  }

  String getLiveCareType(BuildContext context, int callType) {
    switch (callType) {
      case 1:
        return LocaleKeys.videoCall.tr(context: context);
      case 2:
        return LocaleKeys.audioCall.tr(context: context);
      case 3:
        return LocaleKeys.phoneCall.tr(context: context);
      default:
        return LocaleKeys.videoCall.tr(context: context);
    }
  }
}
