import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;

import 'package:clarity_flutter/clarity_flutter.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/api_consts.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/calender_utils_new.dart';
import 'package:hmg_patient_app_new/core/utils/date_util.dart';
import 'package:hmg_patient_app_new/core/utils/penguin_method_channel.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/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/ask_doctor/ask_doctor_view_model.dart';
import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart';
import 'package:hmg_patient_app_new/features/book_appointments/models/resp_models/doctors_list_response_model.dart';
import 'package:hmg_patient_app_new/features/contact_us/contact_us_view_model.dart';
import 'package:hmg_patient_app_new/features/contact_us/models/feedback_type.dart';
import 'package:hmg_patient_app_new/features/hospital/AppPermission.dart';
import 'package:hmg_patient_app_new/features/lab/lab_view_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/patient_appointment_history_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/utils/appointment_type.dart';
import 'package:hmg_patient_app_new/features/prescriptions/models/resp_models/patient_prescriptions_response_model.dart';
import 'package:hmg_patient_app_new/features/prescriptions/prescriptions_view_model.dart';
import 'package:hmg_patient_app_new/features/radiology/radiology_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/appointments/appointment_payment_page.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/appointment_checkin_bottom_sheet.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/appointment_doctor_card.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/appointment_rating_widget.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/ask_doctor_request_type_select.dart';
import 'package:hmg_patient_app_new/presentation/ask_doctor/doctor_response_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/widgets/appointment_calendar.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/widgets/bell_switch.dart';
import 'package:hmg_patient_app_new/presentation/contact_us/feedback_page.dart';
import 'package:hmg_patient_app_new/presentation/prescriptions/prescription_detail_page.dart';
import 'package:hmg_patient_app_new/services/clarity_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:lottie/lottie.dart';
import 'package:map_launcher/map_launcher.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

import '../medical_file/widgets/medical_file_card.dart';

class AppointmentDetailsPage extends StatefulWidget {
  const AppointmentDetailsPage({super.key, required this.patientAppointmentHistoryResponseModel});

  final PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel;

  @override
  State<AppointmentDetailsPage> createState() => _AppointmentDetailsPageState();
}

class _AppointmentDetailsPageState extends State<AppointmentDetailsPage> {
  late MyAppointmentsViewModel myAppointmentsViewModel;
  late PrescriptionsViewModel prescriptionsViewModel;
  late BookAppointmentsViewModel bookAppointmentsViewModel;
  late ContactUsViewModel contactUsViewModel;
  late LabViewModel labViewModel;
  late RadiologyViewModel radiologyViewModel;

  String mapURL = "";

  bool isAppointmentWithin4Hours = false;

  // Countdown timer variables
  Timer? _countdownTimer;
  Duration? _timeRemaining;
  String _countdownText = "";
  Function(void Function())? _modalSetState; // Callback for modal state updates

  // GlobalKey for BellAnimatedSwitch to control it programmatically
  final GlobalKey<BellAnimatedSwitchState> _bellSwitchKey = GlobalKey<BellAnimatedSwitchState>();

  @override
  void initState() {
    Clarity.setCurrentScreenName('Appointment Details Page');
    super.initState();

    scheduleMicrotask(() async {
      if (AppointmentType.isArrived(widget.patientAppointmentHistoryResponseModel)) {
        myAppointmentsViewModel.getDoctorsRatingCheck(
            doctorID: widget.patientAppointmentHistoryResponseModel.doctorID,
            clinicID: widget.patientAppointmentHistoryResponseModel.clinicID,
            projectID: widget.patientAppointmentHistoryResponseModel.projectID,
            appointmentNo: widget.patientAppointmentHistoryResponseModel.appointmentNo);
      } else {
        Duration difference = DateUtil.convertStringToDate(widget.patientAppointmentHistoryResponseModel.appointmentDate).difference(DateTime.now());
        if (difference.inMinutes > 240) {
          isAppointmentWithin4Hours = false;
        } else {
          isAppointmentWithin4Hours = true;
        }

        // // Check if reminder exists in calendar and update the flag
      }
    });

    // Initialize countdown timer for payment after first frame to ensure context is available
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if (mounted) {
        _startCountdownTimer();
        // await _checkAndUpdateReminderStatus();
      }
    });
  }

  /// Checks if a reminder exists in the calendar for this appointment
  /// and updates the hasReminder flag accordingly
  Future<void> _checkAndUpdateReminderStatus() async {
    try {
      CalenderUtilsNew calender = CalenderUtilsNew.instance;

      // Check if reminder exists for this appointment
      bool reminderExists = await calender.checkIfEventExist(
        widget.patientAppointmentHistoryResponseModel.appointmentNo.toString() ?? "",
      );

      // Update the flag if it's different from current state
      if (mounted && widget.patientAppointmentHistoryResponseModel.hasReminder != reminderExists) {
        setState(() {
          widget.patientAppointmentHistoryResponseModel.hasReminder = reminderExists;
        });

        // Also update in view model to keep data consistent
        myAppointmentsViewModel.setAppointmentReminder(reminderExists, widget.patientAppointmentHistoryResponseModel);
      }

      debugPrint("Reminder status for appointment ${widget.patientAppointmentHistoryResponseModel.appointmentNo}: $reminderExists");
      setState(() {});
    } catch (e) {
      debugPrint("Error checking reminder status: $e");
      // If there's an error, default to false
      if (mounted) {
        setState(() {
          widget.patientAppointmentHistoryResponseModel.hasReminder = false;
        });
      }
    }
  }

  void _startCountdownTimer() {
    final appointmentDate = DateUtil.convertStringToDate(widget.patientAppointmentHistoryResponseModel.appointmentDate);
    _updateTimeRemaining();

    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (mounted) {
        _updateTimeRemaining();
      } else {
        timer.cancel();
      }
    });
  }

  void _updateTimeRemaining() {
    final appointmentDate = DateUtil.convertStringToDate(widget.patientAppointmentHistoryResponseModel.appointmentDate);
    final now = DateTime.now();
    final difference = appointmentDate.difference(now);

    if (difference.isNegative) {
      if (mounted) {
        setState(() {
          _timeRemaining = Duration.zero;
          _countdownText = LocaleKeys.appointmentTimePassed.tr(context: context);
        });
      }
      // Also update modal if callback is available
      _modalSetState?.call(() {
        _timeRemaining = Duration.zero;
        _countdownText = LocaleKeys.appointmentTimePassed.tr(context: context);
      });
      _countdownTimer?.cancel();
    } else {
      if (mounted) {
        setState(() {
          _timeRemaining = difference;
          _countdownText = _formatDuration(difference);
        });
      }
      // Also update modal if callback is available
      _modalSetState?.call(() {
        _timeRemaining = difference;
        _countdownText = _formatDuration(difference);
      });
    }
  }

  String _formatDuration(Duration duration) {
    final days = duration.inDays;
    final hours = duration.inHours.remainder(24);
    final minutes = duration.inMinutes.remainder(60);
    final seconds = duration.inSeconds.remainder(60);

    // Format: DD : HH : MM : SS
    return '${days.toString().padLeft(2, '0')} : ${hours.toString().padLeft(2, '0')} : ${minutes.toString().padLeft(2, '0')} : ${seconds.toString().padLeft(2, '0')}';
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    super.dispose();
  }

  // Helper method to build each time unit (number + label)
  Widget _buildTimeUnit(String value, String label) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          alignment: Alignment.center,
          child: value.toText32(
            isBold: true,
            color: AppColors.blackColor,
            isEnglishOnly: true,
          ),
        ),
        SizedBox(height: 4.h),
        Container(
          alignment: Alignment.center,
          child: label.toText12(
            color: AppColors.greyTextColor,
          ),
        ),
      ],
    );
  }

  // Helper method to build time separator (:)
  Widget _buildTimeSeparator() {
    return Padding(
      padding: EdgeInsets.only(bottom: 16.h, left: 6.w, right: 6.w),
      child: ':'.toText32(
        isBold: true,
        color: AppColors.blackColor,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    myAppointmentsViewModel = Provider.of<MyAppointmentsViewModel>(context, listen: false);
    prescriptionsViewModel = Provider.of<PrescriptionsViewModel>(context, listen: false);
    bookAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);
    contactUsViewModel = Provider.of<ContactUsViewModel>(context, listen: false);
    labViewModel = Provider.of<LabViewModel>(context, listen: false);
    radiologyViewModel = Provider.of<RadiologyViewModel>(context, listen: false);
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Column(
        children: [
          Expanded(
            child: CollapsingListView(
              title: LocaleKeys.appointmentDetails.tr(context: context),
              report: AppointmentType.isArrived(widget.patientAppointmentHistoryResponseModel) &&
                      widget.patientAppointmentHistoryResponseModel.isLiveCareAppointment == false &&
                      widget.patientAppointmentHistoryResponseModel.isClinicReBookingAllowed! == true &&
                      widget.patientAppointmentHistoryResponseModel.isActiveDoctor! == true
                  ? () {
                      contactUsViewModel.setSelectedFeedbackType(FeedbackType(id: 1, nameEN: "Complaint for appointment", nameAR: 'شكوى على موعد'));
                      contactUsViewModel.setPatientFeedbackSelectedAppointment(widget.patientAppointmentHistoryResponseModel);
                      contactUsViewModel.setIsSendFeedbackTabSelected(true);
                      Navigator.of(context).push(
                        CustomPageRoute(
                          page: FeedbackPage(),
                        ),
                      );
                    }
                  : null,
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    AppointmentDoctorCard(
                      // renderWidgetForERDisplay: ((widget.patientAppointmentHistoryResponseModel.isLiveCareAppointment ?? false) ||
                      renderWidgetForERDisplay: ((widget.patientAppointmentHistoryResponseModel.isExecludeDoctor ?? false) ||
                          !Utils.isClinicAllowedForRebook(widget.patientAppointmentHistoryResponseModel.clinicID ?? 0)),
                      patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel,
                      onAskDoctorTap: () async {
                        LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingDoctorAvailability.tr(context: context));
                        await myAppointmentsViewModel.isDoctorAvailable(
                            projectID: widget.patientAppointmentHistoryResponseModel.projectID,
                            doctorId: widget.patientAppointmentHistoryResponseModel.doctorID,
                            clinicId: widget.patientAppointmentHistoryResponseModel.clinicID,
                            onSuccess: (value) async {
                              if (value) {
                                await myAppointmentsViewModel.getAskDoctorRequestTypes(onSuccess: (val) {
                                  LoaderBottomSheet.hideLoader();
                                  showCommonBottomSheetWithoutHeight(
                                    context,
                                    title: LocaleKeys.askDoctor.tr(context: context),
                                    child: AskDoctorRequestTypeSelect(
                                      askDoctorRequestTypeList: myAppointmentsViewModel.askDoctorRequestTypeList,
                                      myAppointmentsViewModel: myAppointmentsViewModel,
                                      patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel,
                                    ),
                                    callBackFunc: () {},
                                    isFullScreen: false,
                                    isCloseButtonVisible: true,
                                  );
                                });
                              } else {
                                debugPrint("Doctor is not available");
                              }
                            });
                      },
                      onCancelTap: () async {
                        showCommonBottomSheetWithoutHeight(
                          title: LocaleKeys.notice.tr(context: context),
                          context,
                          child: Utils.getWarningWidget(
                              loadingText: LocaleKeys.cancelAppointmentConfirmMessage.tr(context: context),
                              isShowActionButtons: true,
                              onCancelTap: () {
                                Navigator.of(context).pop();
                              },
                              onConfirmTap: () async {
                                Navigator.of(context).pop();
                                LoaderBottomSheet.showLoader(loadingText: LocaleKeys.cancellingAppointmentPleaseWait.tr(context: context));
                                myAppointmentsViewModel.onTabChange(0);
                                myAppointmentsViewModel.updateListWRTTab(0);
                                await myAppointmentsViewModel.cancelAppointment(
                                    patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel,
                                    onSuccess: (apiResponse) async {
                                      LoaderBottomSheet.hideLoader();
                                      myAppointmentsViewModel.setIsAppointmentDataToBeLoaded(true);
                                      myAppointmentsViewModel.getPatientAppointments(true, false);
                                      showCommonBottomSheet(
                                        context,
                                        child: Utils.getSuccessWidget(loadingText: LocaleKeys.appointmentCancelledSuccessfully.tr(context: context)),
                                        callBackFunc: (str) {
                                          Navigator.of(context).pop();
                                        },
                                        title: "",
                                        isCloseButtonVisible: false,
                                        isDismissible: false,
                                        isFullScreen: false,
                                        isAutoDismiss: true,
                                        height: ResponsiveExtension.screenHeight * 0.3,
                                      );
                                    },
                                    onError: (err) {
                                      LoaderBottomSheet.hideLoader();
                                      showCommonBottomSheetWithoutHeight(context,
                                          child: Utils.getErrorWidget(loadingText: err.toString()),
                                          callBackFunc: () {},
                                          title: "",
                                          isCloseButtonVisible: true,
                                          isDismissible: false,
                                          isFullScreen: false);
                                    });
                              }),
                          callBackFunc: () {},
                          isFullScreen: false,
                          isCloseButtonVisible: true,
                        );
                      },
                      onRescheduleTap: () async {
                        openDoctorScheduleCalendar();
                      },
                      timerWidget: (_timeRemaining == null || _timeRemaining == Duration.zero)
                          ? null
                          : Column(
                              children: [
                                SizedBox(height: 16.w),
                                Divider(height: 1, color: AppColors.dividerColor),
                                SizedBox(height: 16.w),
                                Directionality(
                                  textDirection: ui.TextDirection.ltr,
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Expanded(
                                        child: _buildTimeUnit(
                                          _timeRemaining!.inDays.toString().padLeft(2, '0'),
                                          LocaleKeys.days.tr(context: context),
                                        ),
                                      ),
                                      _buildTimeSeparator(),
                                      Expanded(
                                        child: _buildTimeUnit(
                                          _timeRemaining!.inHours.remainder(24).toString().padLeft(2, '0'),
                                          LocaleKeys.hours.tr(context: context),
                                        ),
                                      ),
                                      _buildTimeSeparator(),
                                      Expanded(
                                        child: _buildTimeUnit(
                                          _timeRemaining!.inMinutes.remainder(60).toString().padLeft(2, '0'),
                                          LocaleKeys.minutes.tr(context: context),
                                        ),
                                      ),
                                      _buildTimeSeparator(),
                                      Expanded(
                                        child: _buildTimeUnit(
                                          _timeRemaining!.inSeconds.remainder(60).toString().padLeft(2, '0'),
                                          LocaleKeys.seconds.tr(context: context),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                SizedBox(height: 16.h),
                                Row(
                                  mainAxisSize: MainAxisSize.max,
                                  children: [
                                    Utils.buildSvgWithAssets(
                                        icon: AppAssets.prescription_reminder_icon, width: 40.w, height: 40.h, applyThemeColor: false),
                                    SizedBox(width: 8.w),
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      spacing: 4.h,
                                      children: [
                                        LocaleKeys.setReminder.tr(context: context).toText13(isBold: true),
                                        LocaleKeys.notifyMeBeforeAppointment
                                            .tr(context: context)
                                            .toText11(color: AppColors.textColorLight, isBold: true),
                                      ],
                                    ),
                                    const Spacer(),
                                    BellAnimatedSwitch(
                                      key: _bellSwitchKey,
                                      width: 56.w,
                                      height: 38.h,
                                      initialValue: widget.patientAppointmentHistoryResponseModel.hasReminder ?? false,
                                      activeColor: AppColors.successColor.withOpacity(0.2),
                                      inactiveColor: AppColors.lightGrayBGColor,
                                      activeCircleColor: AppColors.successColor,
                                      inactiveCircleColor: AppColors.greyTextColor,
                                      activeIconColor: AppColors.bgGreenColor,
                                      inactiveIconColor: AppColors.greyTextColor,
                                      activeIcon:
                                          Utils.buildSvgWithAssets(icon: AppAssets.bell, iconColor: AppColors.whiteColor, width: 12.w, height: 12.h),
                                      inactiveIcon:
                                          Utils.buildSvgWithAssets(icon: AppAssets.bell, iconColor: AppColors.whiteColor, width: 12.w, height: 12.h),
                                      onChanged: (newValue) async {
                                        CalenderUtilsNew calender = CalenderUtilsNew.instance;
                                        bool isEventAddedOrRemoved = false;
                                        if (newValue == true) {
                                          DateTime startDate = DateTime.now();
                                          DateTime endDate =
                                              DateUtil.convertStringToDate(widget.patientAppointmentHistoryResponseModel.appointmentDate);

                                          // Show reminder bottom sheet and check if permission was granted
                                          bool permissionGranted = await BottomSheetUtils().showReminderBottomSheet(
                                              context,
                                              endDate,
                                              widget.patientAppointmentHistoryResponseModel.doctorNameObj ?? "",
                                              "${widget.patientAppointmentHistoryResponseModel.appointmentNo}" ?? "",
                                              "",
                                              "",
                                              title: "Appointment with ${widget.patientAppointmentHistoryResponseModel.doctorNameObj}",
                                              description:
                                                  "${widget.patientAppointmentHistoryResponseModel.doctorNameObj} will be having an appointment on ${widget.patientAppointmentHistoryResponseModel.appointmentDate}",
                                              onSuccess: () {
                                                setState(() {
                                                  myAppointmentsViewModel.setAppointmentReminder(
                                                      newValue, widget.patientAppointmentHistoryResponseModel);
                                                });
                                              },
                                              isMultiAllowed: true,
                                              onMultiDateSuccess: (int selectedIndex) async {
                                                isEventAddedOrRemoved = await calender.createOrUpdateEvent(
                                                    title:
                                                        "Appointment Reminder with ${widget.patientAppointmentHistoryResponseModel.doctorNameObj} on ${DateUtil.convertStringToDate(widget.patientAppointmentHistoryResponseModel.appointmentDate)}, Appointment #${widget.patientAppointmentHistoryResponseModel.appointmentNo}",
                                                    description:
                                                        "Appointment Reminder with ${widget.patientAppointmentHistoryResponseModel.doctorNameObj} in ${widget.patientAppointmentHistoryResponseModel.projectName}",
                                                    scheduleDateTime:
                                                        DateUtil.convertStringToDate(widget.patientAppointmentHistoryResponseModel.appointmentDate),
                                                    eventId: "${widget.patientAppointmentHistoryResponseModel.appointmentNo}",
                                                    location: '',
                                                    reminderMinutes: selectedIndex);
                                                setState(() {
                                                  myAppointmentsViewModel.setAppointmentReminder(
                                                      isEventAddedOrRemoved, widget.patientAppointmentHistoryResponseModel);
                                                });
                                              },
                                              isForAppointment: true);

                                          // If permission was not granted, revert the switch back to OFF
                                          if (!permissionGranted) {
                                            _bellSwitchKey.currentState?.setSwitchValue(false);
                                          }
                                        } else {
                                          isEventAddedOrRemoved = await calender.checkAndRemove(
                                            id: "${widget.patientAppointmentHistoryResponseModel.appointmentNo}",
                                          );
                                          setState(() {
                                            myAppointmentsViewModel.setAppointmentReminder(
                                                !isEventAddedOrRemoved, widget.patientAppointmentHistoryResponseModel);
                                          });
                                        }
                                      },
                                    )
                                  ],
                                ).paddingSymmetrical(16.w, 0)
                              ],
                            ),
                    ),
                    SizedBox(height: 16.h),
                    !AppointmentType.isArrived(widget.patientAppointmentHistoryResponseModel)
                        ? Column(
                            children: [
                              Consumer<BookAppointmentsViewModel>(builder: (context, bookAppointmentsVM, child) {
                                return Container(
                                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                    color: AppColors.whiteColor,
                                    borderRadius: 20.r,
                                    hasShadow: false,
                                  ),
                                  child: Padding(
                                    padding: EdgeInsets.all(16.h),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [
                                            Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                LocaleKeys.appointmentStatus.tr(context: context).toText16(isBold: true),
                                                SizedBox(height: 4.h),
                                                (!AppointmentType.isConfirmed(widget.patientAppointmentHistoryResponseModel)
                                                    ? LocaleKeys.notConfirmed
                                                        .tr(context: context)
                                                        .toText12(color: AppColors.primaryRedColor, isBold: true)
                                                    : LocaleKeys.confirmed
                                                        .tr(context: context)
                                                        .toText12(color: AppColors.successColor, isBold: true)),
                                                SizedBox(height: 16.h),
                                              ],
                                            ),
                                          ],
                                        ),
                                        //TODO Add countdown timer in case of LiveCare Appointment
                                        widget.patientAppointmentHistoryResponseModel.isLiveCareAppointment ?? false
                                            ? Row(
                                                children: [
                                                  Utils.buildSvgWithAssets(icon: AppAssets.livecare_clinic_icon, width: 40.h, height: 40.h),
                                                  SizedBox(width: 12.w),
                                                  Expanded(
                                                    child: Column(
                                                      crossAxisAlignment: CrossAxisAlignment.start,
                                                      children: [
                                                        LocaleKeys.doctorWillCallYou
                                                            .tr(context: context)
                                                            .toText14(color: AppColors.greyTextColor, isBold: true),
                                                      ],
                                                    ),
                                                  ),
                                                ],
                                              )
                                            : Stack(
                                                children: [
                                                  SizedBox(
                                                    width: double.infinity,
                                                    child: ClipRRect(
                                                      clipBehavior: Clip.hardEdge,
                                                      borderRadius: BorderRadius.circular(24.r),
                                                      // Todo: what is this???? Api Key??? 😲
                                                      child: Utils.buildImgWithNetwork(
                                                        url: "https://maps.googleapis.com/maps/api/staticmap?center=${widget.patientAppointmentHistoryResponseModel.latitude},${widget.patientAppointmentHistoryResponseModel.longitude}&zoom=14&size=${(MediaQuery.of(context).size.width * 1.5).toInt()}x${(MediaQuery.of(context).size.height * 0.35).toInt()}&maptype=roadmap&markers=color:red%7C${widget.patientAppointmentHistoryResponseModel.latitude},${widget.patientAppointmentHistoryResponseModel.longitude}&key=${ApiKeyConstants.googleMapsApiKey}",
                                                        iconColor: AppColors.transparent,
                                                        fit: BoxFit.cover,
                                                        width: double.infinity,
                                                          height: 180.h),
                                                    ),
                                                  ),
                                                  Positioned(
                                                    bottom: 0,
                                                    child: SizedBox(
                                                      width: MediaQuery.of(context).size.width - 85.w,
                                                      child: CustomButton(
                                                        onPressed: () async {
                                                          if (widget.patientAppointmentHistoryResponseModel.projectID == 130 ||
                                                              widget.patientAppointmentHistoryResponseModel.projectID == 120) {
                                                            showDirectionsBottomSheet();
                                                          } else {
                                                            await MapLauncher.showMarker(
                                                              mapType: MapType.google,
                                                              coords: Coords(double.parse(widget.patientAppointmentHistoryResponseModel.latitude!),
                                                                  double.parse(widget.patientAppointmentHistoryResponseModel.longitude!)),
                                                              title: widget.patientAppointmentHistoryResponseModel.projectName ?? "Habib Hospital",
                                                            ).catchError((err) {
                                                              MapLauncher.showMarker(
                                                                mapType: Platform.isIOS ? MapType.apple : MapType.google,
                                                                coords: Coords(double.parse(widget.patientAppointmentHistoryResponseModel.latitude!),
                                                                    double.parse(widget.patientAppointmentHistoryResponseModel.longitude!)),
                                                                title: widget.patientAppointmentHistoryResponseModel.projectName ?? "Habib Hospital",
                                                              );
                                                            });
                                                          }
                                                        },
                                                        text: LocaleKeys.getDirections.tr(context: context),
                                                        backgroundColor: AppColors.bookAppointment.withValues(alpha: 0.8),
                                                        borderColor: AppointmentType.getNextActionButtonColor(
                                                                widget.patientAppointmentHistoryResponseModel.nextAction)
                                                            .withValues(alpha: 0.01),
                                                        textColor: Colors.white,
                                                        fontSize: 14.f,
                                                        fontWeight: FontWeight.w600,
                                                        borderRadius: 12.r,
                                                        padding: EdgeInsets.symmetric(horizontal: 10.w),
                                                        height: 40.h,
                                                        icon: AppAssets.directions_icon,
                                                        iconColor: Colors.white,
                                                        iconSize: 14.h,
                                                      ).paddingAll(12.h),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                        SizedBox(height: 8.h),
                                        bookAppointmentsViewModel.appointmentNearestGateResponseModel != null
                                            ? Wrap(
                                                direction: Axis.horizontal,
                                                spacing: 8.w,
                                                runSpacing: 8.h,
                                                children: [
                                                  AppCustomChipWidget(
                                                    labelText: bookAppointmentsVM.isAppointmentNearestGateLoading
                                                        ? "Floor: Ground Floor"
                                                        : "${LocaleKeys.floor.tr(context: context)}: ${getIt.get<AppState>().isArabic() ? bookAppointmentsViewModel.appointmentNearestGateResponseModel!.clinicLocationN : bookAppointmentsViewModel.appointmentNearestGateResponseModel!.clinicLocation}",
                                                  ).toShimmer2(isShow: bookAppointmentsVM.isAppointmentNearestGateLoading),
                                                  AppCustomChipWidget(
                                                          labelText:
                                                              "${LocaleKeys.nearestGate.tr(context: context)}: ${getIt.get<AppState>().isArabic() ? bookAppointmentsVM.appointmentNearestGateResponseModel!.nearestGateNumberN : bookAppointmentsVM.appointmentNearestGateResponseModel!.nearestGateNumber}")
                                                      .toShimmer2(isShow: bookAppointmentsVM.isAppointmentNearestGateLoading),
                                                ],
                                              )
                                            : SizedBox.shrink(),
                                      ],
                                    ),
                                  ),
                                );
                              }),
                              SizedBox(height: 16.h),
                              SizedBox(height: 16.h),
                            ],
                          )
                        // : SizedBox.shrink()
                        : Consumer<MyAppointmentsViewModel>(builder: (context, myAppointmentsVM, child) {
                            return GridView(
                              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 3,
                                crossAxisSpacing: 16.h,
                                mainAxisSpacing: 16.w,
                                childAspectRatio: isFoldable ? 1.2 : (isTablet ? 1.4 : 0.98),
                              ),
                              physics: NeverScrollableScrollPhysics(),
                              padding: EdgeInsets.zero,
                              shrinkWrap: true,
                              children: [
                                MedicalFileCard(
                                  label: LocaleKeys.labResults.tr(context: context),
                                  textColor: AppColors.blackColor,
                                  backgroundColor: AppColors.whiteColor,
                                  svgIcon: AppAssets.lab_result_icon,
                                  isLargeText: true,
                                  iconSize: 36.w,
                                ).onPress(() async {
                                  LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingLabResults.tr(context: context));
                                  await labViewModel.getLabResultsByAppointmentNo(
                                    appointmentNo: widget.patientAppointmentHistoryResponseModel.appointmentNo,
                                    projectID: widget.patientAppointmentHistoryResponseModel.projectID,
                                    clinicID: widget.patientAppointmentHistoryResponseModel.clinicID,
                                    doctorID: widget.patientAppointmentHistoryResponseModel.doctorID,
                                    doctorName: widget.patientAppointmentHistoryResponseModel.doctorNameObj!,
                                    clinicName: widget.patientAppointmentHistoryResponseModel.clinicName!,
                                    projectName: widget.patientAppointmentHistoryResponseModel.projectName!,
                                    appointmentDate: widget.patientAppointmentHistoryResponseModel.appointmentDate!,
                                    onSuccess: (val) {
                                      LoaderBottomSheet.hideLoader();
                                    },
                                    onError: (err) {
                                      LoaderBottomSheet.hideLoader();
                                      showCommonBottomSheetWithoutHeight(
                                        context,
                                        child: Utils.getErrorWidget(loadingText: err),
                                        callBackFunc: () {},
                                        isFullScreen: false,
                                        isCloseButtonVisible: true,
                                      );
                                    },
                                  );
                                }),
                                MedicalFileCard(
                                  label: "${LocaleKeys.radiology.tr(context: context)} ${LocaleKeys.radiologySubtitle.tr(context: context)}",
                                  textColor: AppColors.blackColor,
                                  backgroundColor: AppColors.whiteColor,
                                  svgIcon: AppAssets.radiology_icon,
                                  isLargeText: true,
                                  iconSize: 36.w,
                                ).onPress(() async {
                                  LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingRadiologyResults.tr(context: context));
                                  await radiologyViewModel.getPatientRadiologyOrdersByAppointment(
                                    appointmentNo: widget.patientAppointmentHistoryResponseModel.appointmentNo,
                                    projectID: widget.patientAppointmentHistoryResponseModel.projectID,
                                    onSuccess: (val) {
                                      LoaderBottomSheet.hideLoader();
                                    },
                                    onError: (err) {
                                      LoaderBottomSheet.hideLoader();
                                      showCommonBottomSheetWithoutHeight(
                                        context,
                                        child: Utils.getErrorWidget(loadingText: err),
                                        callBackFunc: () {},
                                        isFullScreen: false,
                                        isCloseButtonVisible: true,
                                      );
                                    },
                                  );
                                }),
                                MedicalFileCard(
                                  label: LocaleKeys.prescriptions.tr(context: context),
                                  textColor: AppColors.blackColor,
                                  backgroundColor: AppColors.whiteColor,
                                  svgIcon: AppAssets.prescription_item_icon,
                                  isLargeText: true,
                                  iconSize: 36.w,
                                ).onPress(() async {
                                  LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingAppointmentPrescriptions.tr(context: context));
                                  await prescriptionsViewModel.getPrescriptionDetails(
                                    getPrescriptionRequestModel(),
                                    onSuccess: (val) {
                                      LoaderBottomSheet.hideLoader();
                                      if (val.data.isNotEmpty) {
                                        PatientPrescriptionsResponseModel patientPrescriptionsResponseModel = PatientPrescriptionsResponseModel(
                                          doctorImageURL: widget.patientAppointmentHistoryResponseModel.doctorImageURL,
                                          doctorName: widget.patientAppointmentHistoryResponseModel.doctorNameObj,
                                          appointmentDate: widget.patientAppointmentHistoryResponseModel.appointmentDate,
                                          clinicDescription: widget.patientAppointmentHistoryResponseModel.clinicName,
                                          decimalDoctorRate: widget.patientAppointmentHistoryResponseModel.decimalDoctorRate,
                                          name: widget.patientAppointmentHistoryResponseModel.projectName,
                                          isHomeMedicineDeliverySupported: val.data.first.isHomeMedicineDeliverySupported ?? false,
                                          projectID: widget.patientAppointmentHistoryResponseModel.projectID,
                                          clinicID: widget.patientAppointmentHistoryResponseModel.clinicID,
                                          doctorID: widget.patientAppointmentHistoryResponseModel.doctorID,
                                          setupID: widget.patientAppointmentHistoryResponseModel.setupID,
                                          isInOutPatient: widget.patientAppointmentHistoryResponseModel.isInOutPatient,
                                          appointmentNo: widget.patientAppointmentHistoryResponseModel.appointmentNo,
                                          episodeID: widget.patientAppointmentHistoryResponseModel.episodeID,
                                          dischargeNo: 0,
                                        );
                                        Navigator.of(context).push(
                                          CustomPageRoute(
                                            page: PrescriptionDetailPage(
                                                isFromAppointments: true, prescriptionsResponseModel: patientPrescriptionsResponseModel),
                                          ),
                                        );
                                      } else {
                                        showCommonBottomSheetWithoutHeight(
                                          context,
                                          child: Utils.getErrorWidget(loadingText: LocaleKeys.noPrescriptionsForAppointment.tr(context: context)),
                                          callBackFunc: () {},
                                          isFullScreen: false,
                                          isCloseButtonVisible: true,
                                        );
                                      }
                                    },
                                    onError: (err) {
                                      LoaderBottomSheet.hideLoader();
                                      showCommonBottomSheetWithoutHeight(
                                        context,
                                        child: Utils.getErrorWidget(loadingText: LocaleKeys.noPrescriptionsForAppointment.tr(context: context)),
                                        callBackFunc: () {},
                                        isFullScreen: false,
                                        isCloseButtonVisible: true,
                                      );
                                    },
                                  );
                                  // Navigator.of(context).push(
                                  //   CustomPageRoute(
                                  //     page: VaccineListPage(),
                                  //   ),
                                  // );
                                }),
                                MedicalFileCard(
                                  label: LocaleKeys.doctorResponses.tr(context: context),
                                  textColor: AppColors.blackColor,
                                  backgroundColor: AppColors.whiteColor,
                                  svgIcon: AppAssets.ask_doctor_medical_file_icon,
                                  isLargeText: true,
                                  iconSize: 36.w,
                                ).onPress(() {
                                  getIt.get<AskDoctorViewModel>().initAskDoctorViewModel();
                                  getIt.get<AskDoctorViewModel>().getDoctorResponses();
                                  Navigator.of(context).push(
                                    CustomPageRoute(
                                      page: DoctorResponsePage(),
                                    ),
                                  );
                                }),
                                MedicalFileCard(
                                  label: LocaleKeys.viewInvoiceDetails.tr(context: context),
                                  textColor: AppColors.blackColor,
                                  backgroundColor: AppColors.whiteColor,
                                  svgIcon: AppAssets.invoices_list_icon,
                                  isLargeText: true,
                                  iconSize: 36.w,
                                ).onPress(() {
                                  LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingInvoiceDetails.tr(context: context));
                                  myAppointmentsViewModel.getAppointmentInvoice(
                                    appointmentNum: widget.patientAppointmentHistoryResponseModel.appointmentNo,
                                    onSuccess: (val) {
                                      LoaderBottomSheet.hideLoader();
                                    },
                                    onError: (err) {
                                      LoaderBottomSheet.hideLoader();
                                      showCommonBottomSheetWithoutHeight(
                                        context,
                                        child: Utils.getErrorWidget(loadingText: err),
                                        callBackFunc: () {},
                                        isFullScreen: false,
                                        isCloseButtonVisible: true,
                                      );
                                    },
                                  );
                                }),
                                myAppointmentsVM.isAppointmentRatedResponseLoading
                                    ? MedicalFileCard(
                                        label: "Medical File",
                                        textColor: AppColors.blackColor,
                                        backgroundColor: AppColors.whiteColor,
                                        svgIcon: AppAssets.appointmentRatingIcon,
                                        isLargeText: true,
                                        iconSize: 36.w,
                                        isLocked: false,
                                      ).toShimmer2()
                                    : myAppointmentsVM.appointmentRatedResponseModel != null
                                        ? MedicalFileCard(
                                            label: !(myAppointmentsVM.appointmentRatedResponseModel!.isAllowedToRate ?? false)
                                                ? LocaleKeys.ratingSubmitted.tr(context: context)
                                                : LocaleKeys.doctorRatingAppointment.tr(context: context),
                                            textColor: AppColors.blackColor,
                                            backgroundColor: AppColors.whiteColor,
                                            svgIcon: AppAssets.appointmentRatingIcon,
                                            isLargeText: true,
                                            iconSize: 36.w,
                                            isLocked: !(myAppointmentsVM.appointmentRatedResponseModel!.isAllowedToRate ?? false),
                                          ).onPress(() {
                                            if (myAppointmentsVM.appointmentRatedResponseModel?.isAllowedToRate ?? false) {
                                              showCommonBottomSheetWithoutHeight(
                                                context,
                                                title: LocaleKeys.doctorRating.tr(context: context),
                                                isCloseButtonVisible: true,
                                                child: StatefulBuilder(
                                                  builder: (context, setState) {
                                                    return AppointmentRatingWidget(
                                                      patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel,
                                                    );
                                                  },
                                                ),
                                                callBackFunc: () {
                                                  myAppointmentsViewModel.getDoctorsRatingCheck(
                                                      doctorID: widget.patientAppointmentHistoryResponseModel.doctorID,
                                                      clinicID: widget.patientAppointmentHistoryResponseModel.clinicID,
                                                      projectID: widget.patientAppointmentHistoryResponseModel.projectID,
                                                      appointmentNo: widget.patientAppointmentHistoryResponseModel.appointmentNo);
                                                },
                                                isFullScreen: false,
                                              );
                                            }
                                          })
                                        : SizedBox.shrink(),
                                (widget.patientAppointmentHistoryResponseModel.isParkingAvailable ?? false)
                                    ? MedicalFileCard(
                                        label: LocaleKeys.getParkingQR.tr(context: context),
                                        textColor: AppColors.blackColor,
                                        backgroundColor: AppColors.whiteColor,
                                        svgIcon: AppAssets.appointment_parking_icon,
                                        isLargeText: true,
                                        iconSize: 36.w,
                                      ).onPress(() {
                                        LoaderBottomSheet.showLoader(loadingText: LocaleKeys.loadingText.tr(context: context));
                                        myAppointmentsViewModel.getParkingQR(
                                          widget.patientAppointmentHistoryResponseModel.appointmentNo,
                                          widget.patientAppointmentHistoryResponseModel.projectID,
                                          onSuccess: (val) {
                                            LoaderBottomSheet.hideLoader();
                                            showCommonBottomSheetWithoutHeight(
                                              title: LocaleKeys.parkingQR.tr(context: context),
                                              context,
                                              child: Column(
                                                children: [
                                                  LocaleKeys.parkingQRDesc.tr(context: context).toText16(),
                                                  SizedBox(height: 16.h),
                                                  Image.memory(
                                                    myAppointmentsViewModel.parkingQRImageBytes!,
                                                    width: 156.w,
                                                    height: 156.h,
                                                    fit: BoxFit.cover,
                                                    gaplessPlayback: true, // Prevents blink during image rebuild
                                                  ),
                                                  SizedBox(height: 16.h),
                                                  CustomButton(
                                                    text: LocaleKeys.done.tr(context: context),
                                                    onPressed: () {
                                                      openDoctorScheduleCalendar();
                                                    },
                                                    backgroundColor: AppColors.primaryRedColor,
                                                    borderColor: AppColors.primaryRedColor,
                                                    textColor: Colors.white,
                                                    fontSize: 16.f,
                                                    fontWeight: FontWeight.w600,
                                                    borderRadius: 12.r,
                                                    padding: EdgeInsets.symmetric(horizontal: 10.w),
                                                    height: 50.h,
                                                    icon: AppAssets.checkmark_icon,
                                                    iconColor: Colors.white,
                                                    iconSize: 18.h,
                                                  ).paddingSymmetrical(0.h, 0.h),
                                                ],
                                              ),
                                              callBackFunc: () {},
                                              isFullScreen: false,
                                              isCloseButtonVisible: true,
                                            );
                                          },
                                          onError: (err) {
                                            LoaderBottomSheet.hideLoader();
                                            showCommonBottomSheetWithoutHeight(
                                              context,
                                              child: Utils.getErrorWidget(loadingText: err),
                                              callBackFunc: () {},
                                              isFullScreen: false,
                                              isCloseButtonVisible: true,
                                            );
                                          },
                                        );
                                      })
                                    : SizedBox.shrink(),
                              ],
                            );
                          }),
                  ],
                ).paddingAll(24.w),
              ),
            ),
          ),
          Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.whiteColor,
              borderRadius: 24.r,
              hasShadow: true,
            ),
            child: SizedBox(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if (widget.patientAppointmentHistoryResponseModel.nextAction == 15 ||
                      widget.patientAppointmentHistoryResponseModel.nextAction == 20)
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            LocaleKeys.amountBeforeTax.tr(context: context).toText18(isBold: true),
                            Utils.getPaymentAmountWithSymbol(
                                widget.patientAppointmentHistoryResponseModel.patientShare!.toString().toText16(isBold: true),
                                AppColors.blackColor,
                                13,
                                isSaudiCurrency: true),
                          ],
                        ),
                        SizedBox(height: 4.h),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                                child: LocaleKeys.upcomingPaymentNow.tr(context: context).toText12(isBold: true, color: AppColors.greyTextColor)),
                            "VAT 15%(${widget.patientAppointmentHistoryResponseModel.patientTaxAmount})"
                                .toText14(isBold: true, color: AppColors.greyTextColor, letterSpacing: -0.64),
                          ],
                        ),
                        SizedBox(height: 18.h),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Utils.getPaymentMethods(),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Utils.getPaymentAmountWithSymbol(
                                    widget.patientAppointmentHistoryResponseModel.patientShareWithTax!.toString().toText24(isBold: true),
                                    AppColors.blackColor,
                                    17,
                                    isSaudiCurrency: true),
                              ],
                            ),
                          ],
                        )
                      ],
                    ).paddingOnly(left: 16.h, top: 24.h, right: 16.h, bottom: 0.h),
                  AppointmentType.isArrived(widget.patientAppointmentHistoryResponseModel)
                      ? (!(widget.patientAppointmentHistoryResponseModel.isActiveDoctor ?? true) ||
                              widget.patientAppointmentHistoryResponseModel.isLiveCareAppointment! ||
                              widget.patientAppointmentHistoryResponseModel.isExecludeDoctor! ||
                              widget.patientAppointmentHistoryResponseModel.isClinicReBookingAllowed == false ||
                              !Utils.isClinicAllowedForRebook(widget.patientAppointmentHistoryResponseModel.clinicID))
                          ? SizedBox.shrink()
                          : CustomButton(
                              text: LocaleKeys.rebookAppointment.tr(context: context),
                              onPressed: () {
                                openDoctorScheduleCalendar();
                              },
                              backgroundColor: AppColors.primaryRedColor,
                              borderColor: AppColors.primaryRedColor,
                              textColor: Colors.white,
                              fontSize: 16.f,
                              fontWeight: FontWeight.w600,
                              borderRadius: 12.r,
                              padding: EdgeInsets.symmetric(horizontal: 10.w),
                              height: 50.h,
                              icon: AppAssets.add_icon,
                              iconColor: Colors.white,
                              iconSize: 18.h,
                            ).paddingSymmetrical(16.h, 24.h)
                      : CustomButton(
                          text: AppointmentType.getNextActionText(widget.patientAppointmentHistoryResponseModel.nextAction),
                          onPressed: () {
                            handleAppointmentNextAction(widget.patientAppointmentHistoryResponseModel.nextAction);
                          },
                          backgroundColor: AppointmentType.getNextActionButtonColor(widget.patientAppointmentHistoryResponseModel.nextAction),
                          borderColor: AppointmentType.getNextActionButtonColor(widget.patientAppointmentHistoryResponseModel.nextAction)
                              .withValues(alpha: 0.01),
                          textColor: widget.patientAppointmentHistoryResponseModel.nextAction == 15 ? AppColors.textColor : Colors.white,
                          fontSize: 16.f,
                          fontWeight: FontWeight.w600,
                          borderRadius: 12.r,
                          padding: EdgeInsets.symmetric(horizontal: 10.w),
                          height: 56.h,
                          icon: AppointmentType.getNextActionIcon(widget.patientAppointmentHistoryResponseModel.nextAction),
                          iconColor: Colors.white,
                          iconSize: 18.h,
                        ).paddingSymmetrical(16.h, 24.h),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  void showDirectionsBottomSheet() {
    showCommonBottomSheetWithoutHeight(
      context,
      title: "",
      isDismissible: true,
      isCloseButtonVisible: false,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          LocaleKeys.confirmYourLocation.tr(context: context).toText28(color: AppColors.textColor, isBold: true, height: 1.5),
          SizedBox(height: 4.h),
          LocaleKeys.confirmYourLocationDesc.tr(context: context).toText12(
                color: AppColors.greyTextColor,
                isBold: true,
              ),
          SizedBox(height: 24.h),
          CustomButton(
            text: LocaleKeys.insideHospital.tr(context: context),
            onPressed: () {
              Navigator.pop(context);
              initPenguinSDK(
                  widget.patientAppointmentHistoryResponseModel.projectID == 130
                      ? 1
                      : (widget.patientAppointmentHistoryResponseModel.projectID == 120 ? 3 : -1),
                  clinicID: widget.patientAppointmentHistoryResponseModel.clinicID.toString());
            },
            backgroundColor: AppColors.primaryRedColor,
            borderColor: AppColors.primaryRedColor,
            textColor: Colors.white,
            fontSize: 16.f,
            fontWeight: FontWeight.w600,
            borderRadius: 12.r,
            // padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
            height: 56.h,
          ),
          SizedBox(height: 8.h),
          CustomButton(
            text: LocaleKeys.outsideHospital.tr(context: context),
            onPressed: () async {
              Navigator.pop(context);
              await MapLauncher.showMarker(
                mapType: MapType.google,
                coords: Coords(double.parse(widget.patientAppointmentHistoryResponseModel.latitude!),
                    double.parse(widget.patientAppointmentHistoryResponseModel.longitude!)),
                title: widget.patientAppointmentHistoryResponseModel.projectName ?? "Habib Hospital",
              ).catchError((err) {
                MapLauncher.showMarker(
                  mapType: Platform.isIOS ? MapType.apple : MapType.google,
                  coords: Coords(double.parse(widget.patientAppointmentHistoryResponseModel.latitude!),
                      double.parse(widget.patientAppointmentHistoryResponseModel.longitude!)),
                  title: widget.patientAppointmentHistoryResponseModel.projectName ?? "Habib Hospital",
                );
              });
            },
            backgroundColor: AppColors.chipSecondaryLightRedColor,
            borderColor: AppColors.chipSecondaryLightRedColor,
            textColor: AppColors.primaryRedColor,
            fontSize: 16.f,
            fontWeight: FontWeight.w600,
            borderRadius: 12.r,
            // padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
            height: 56.h,
          ),
        ],
      ).paddingSymmetrical(24.w, 20.h),
      callBackFunc: () {},
    );
  }

  initPenguinSDK(int projectID, {String clinicID = ""}) async {
    NavigationClinicDetails data = NavigationClinicDetails();
    data.projectId = projectID.toString();
    data.clinicId = clinicID;
    // data.clinicId = "1";
    final bool permited = await AppPermission.askPenguinPermissions();
    if (!permited) {
      Map<Permission, PermissionStatus> statuses = await [
        Permission.location,
        Permission.bluetooth,
        Permission.bluetoothConnect,
        Permission.bluetoothScan,
        Permission.activityRecognition,
      ].request().whenComplete(() {
        PenguinMethodChannel().launch("penguin", getIt.get<AppState>().isArabic() ? "ar" : "en",
            getIt.get<AppState>().getAuthenticatedUser()?.patientId?.toString() ?? "", true,
            details: data);
      });
    }
  }

  openDoctorScheduleCalendar() async {
    DoctorsListResponseModel doctor = DoctorsListResponseModel(
      clinicID: widget.patientAppointmentHistoryResponseModel.clinicID,
      projectID: widget.patientAppointmentHistoryResponseModel.projectID,
      doctorID: widget.patientAppointmentHistoryResponseModel.doctorID,
      doctorImageURL: widget.patientAppointmentHistoryResponseModel.doctorImageURL,
      doctorTitle: widget.patientAppointmentHistoryResponseModel.doctorTitle,
      name: widget.patientAppointmentHistoryResponseModel.doctorNameObj,
      nationalityFlagURL: "",
      speciality: [],
      clinicName: widget.patientAppointmentHistoryResponseModel.clinicName,
      projectName: widget.patientAppointmentHistoryResponseModel.projectName,
    );
    bookAppointmentsViewModel.setSelectedDoctor(doctor);
    bookAppointmentsViewModel.setIsPatientRescheduleAppointment(true);
    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingDoctorSchedulePleaseWait.tr(context: context));
    await bookAppointmentsViewModel.getDoctorFreeSlots(
        isBookingForLiveCare: false,
        onSuccess: (dynamic respData) async {
          LoaderBottomSheet.hideLoader();
          showCommonBottomSheetWithoutHeight(
            title: LocaleKeys.pickADate.tr(context: context),
            context,
            child: AppointmentCalendar(),
            isFullScreen: false,
            isCloseButtonVisible: true,
            callBackFunc: () {},
          );
        },
        onError: (err) {
          LoaderBottomSheet.hideLoader();
          showCommonBottomSheetWithoutHeight(
            context,
            child: Utils.getErrorWidget(loadingText: err),
            callBackFunc: () {},
            isFullScreen: false,
            isCloseButtonVisible: true,
          );
        });
  }

  Future<void> handleAppointmentNextAction(nextAction) async {
    switch (nextAction) {
      case 0:
        break;
      case 10:
        LoaderBottomSheet.showLoader(loadingText: LocaleKeys.confirmingAppointmentPleaseWait.tr(context: context));
        await myAppointmentsViewModel.confirmAppointment(
            patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel,
            onSuccess: (apiResponse) {
              LoaderBottomSheet.hideLoader();
              // myAppointmentsViewModel.setIsAppointmentDataToBeLoaded(true);
              // myAppointmentsViewModel.getPatientAppointments(true, false);
              showCommonBottomSheet(context,
                  child: Utils.getSuccessWidget(loadingText: LocaleKeys.appointmentConfirmedSuccessfully.tr(context: context)), callBackFunc: (str) {
                myAppointmentsViewModel.setIsAppointmentDataToBeLoaded(true);
                myAppointmentsViewModel.initAppointmentsViewModel();
                myAppointmentsViewModel.getPatientAppointments(true, false);
                Navigator.of(context).pop();
              },
                  title: "",
                  height: ResponsiveExtension.screenHeight * 0.3,
                  isAutoDismiss: true,
                  isCloseButtonVisible: true,
                  isDismissible: false,
                  isFullScreen: false,
                  isSuccessDialog: true);
            },
            onError: (err) {
              LoaderBottomSheet.hideLoader();
              showCommonBottomSheetWithoutHeight(
                context,
                child: Utils.getErrorWidget(loadingText: err),
                callBackFunc: () {},
                isFullScreen: false,
                isCloseButtonVisible: true,
              );
            });
      // LoaderBottomSheet.hideLoader();
      case 15:
        // Ensure timer is running before showing modal
        if (_countdownTimer == null || !_countdownTimer!.isActive) {
          _startCountdownTimer();
        }

        showCommonBottomSheetWithoutHeight(
          context,
          title: LocaleKeys.notice.tr(),
          child: StatefulBuilder(
            builder: (context, setModalState) {
              // Store the modal setState callback
              _modalSetState = setModalState;

              return Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Lottie.asset(AppAnimations.warningAnimation,
                      repeat: false, reverse: false, frameRate: FrameRate(60), width: 100.h, height: 100.h, fit: BoxFit.fill),
                  SizedBox(
                    height: 12,
                  ),
                  LocaleKeys.upcomingPaymentPending.tr(context: context).toText14(color: AppColors.textColor, isCenter: true),
                  SizedBox(height: 24.h),
                  // // Countdown Timer - DD : HH : MM : SS format with labels - Always LTR
                  // Directionality(
                  //   textDirection: ui.TextDirection.ltr,
                  //   child: Row(
                  //     mainAxisAlignment: MainAxisAlignment.center,
                  //     crossAxisAlignment: CrossAxisAlignment.start,
                  //     children: [
                  //       // Days
                  //       _buildTimeUnit(
                  //         _timeRemaining != null ? _timeRemaining!.inDays.toString().padLeft(2, '0') : '00',
                  //         LocaleKeys.days.tr(context: context),
                  //       ),
                  //       _buildTimeSeparator(),
                  //       // Hours
                  //       _buildTimeUnit(
                  //         _timeRemaining != null ? _timeRemaining!.inHours.remainder(24).toString().padLeft(2, '0') : '00',
                  //         LocaleKeys.hours.tr(context: context),
                  //       ),
                  //       _buildTimeSeparator(),
                  //       // Minutes
                  //       _buildTimeUnit(
                  //         _timeRemaining != null ? _timeRemaining!.inMinutes.remainder(60).toString().padLeft(2, '0') : '00',
                  //         LocaleKeys.minutes.tr(context: context),
                  //       ),
                  //       _buildTimeSeparator(),
                  //       // Seconds
                  //       _buildTimeUnit(
                  //         _timeRemaining != null ? _timeRemaining!.inSeconds.remainder(60).toString().padLeft(2, '0') : '00',
                  //         LocaleKeys.seconds.tr(context: context),
                  //       ),
                  //     ],
                  //   ),
                  // ),
                  // SizedBox(height: 24.h),
                  // Green Acknowledge button with checkmark icon
                  CustomButton(
                    text: LocaleKeys.acknowledged.tr(context: context),
                    onPressed: () {
                      _modalSetState = null; // Clear callback when closing
                      Navigator.of(context).pop();
                    },
                    backgroundColor: AppColors.successColor,
                    borderColor: AppColors.successColor,
                    textColor: Colors.white,
                    fontSize: 16.f,
                    fontWeight: FontWeight.w600,
                    borderRadius: 12.r,
                    height: 50.h,
                    icon: AppAssets.checkmark_icon,
                    iconColor: Colors.white,
                  ),
                ],
              );
            },
          ),
          callBackFunc: () {
            _modalSetState = null; // Clear callback when closing
          },
          isFullScreen: false,
          isCloseButtonVisible: true,
        );
      case 20:
        myAppointmentsViewModel.setIsPatientAppointmentShareLoading(true);
        Navigator.of(context).push(
          CustomPageRoute(
            page: AppointmentPaymentPage(patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel),
          ),
        );
      case 50:
      // return LocaleKeys.confirmLiveCare.tr(context: context);
      case 90:
        Clarity.setCurrentScreenName('Appointment CheckIn Page');
        showCommonBottomSheetWithoutHeight(context,
            title: LocaleKeys.onlineCheckIn.tr(context: context),
            child: isAppointmentWithin4Hours
                ? AppointmentCheckinBottomSheet(
                    patientAppointmentHistoryResponseModel: widget.patientAppointmentHistoryResponseModel,
                    myAppointmentsViewModel: myAppointmentsViewModel,
                  )
                : Utils.getOnlineCheckInWidget(
                    loadingText: LocaleKeys.onlineCheckIn24HoursOnly.tr(context: context),
                  ), callBackFunc: () {
          Clarity.setCurrentScreenName('Appointment Details Page');
        }, isFullScreen: false);
      default:
      // return "No Action".needTranslation;
    }
  }

  PatientPrescriptionsResponseModel getPrescriptionRequestModel() {
    return PatientPrescriptionsResponseModel(
      appointmentNo: widget.patientAppointmentHistoryResponseModel.appointmentNo,
      setupID: widget.patientAppointmentHistoryResponseModel.setupID,
      episodeID: widget.patientAppointmentHistoryResponseModel.episodeID,
      clinicID: widget.patientAppointmentHistoryResponseModel.clinicID,
      projectID: widget.patientAppointmentHistoryResponseModel.projectID,
      dischargeNo: 0,
      isInOutPatient: widget.patientAppointmentHistoryResponseModel.isInOutPatient,
      isHomeMedicineDeliverySupported: false,
      doctorImageURL: widget.patientAppointmentHistoryResponseModel.doctorImageURL,
      doctorName: "${widget.patientAppointmentHistoryResponseModel.doctorTitle} ${widget.patientAppointmentHistoryResponseModel.doctorNameObj}",
      appointmentDate: widget.patientAppointmentHistoryResponseModel.appointmentDate,
      clinicDescription: widget.patientAppointmentHistoryResponseModel.clinicName,
      decimalDoctorRate: widget.patientAppointmentHistoryResponseModel.decimalDoctorRate,
      name: widget.patientAppointmentHistoryResponseModel.projectName,
    );
  }
}
