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

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:get_it/get_it.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_export.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/date_util.dart';
import 'package:hmg_patient_app_new/core/utils/size_config.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/route_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/book_appointments/models/resp_models/doctors_list_response_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/vital_sign_respo_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/ui_models/vital_sign_ui_model.dart';
import 'package:hmg_patient_app_new/features/insurance/insurance_view_model.dart';
import 'package:hmg_patient_app_new/features/lab/lab_view_model.dart';
import 'package:hmg_patient_app_new/features/medical_file/medical_file_view_model.dart';
import 'package:hmg_patient_app_new/features/medical_file/models/patient_medical_response_model.dart';
import 'package:hmg_patient_app_new/features/medical_file/models/patient_sickleave_response_model.dart';
import 'package:hmg_patient_app_new/features/monthly_report/monthly_report_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_invoices/my_invoices_view_model.dart';
import 'package:hmg_patient_app_new/features/prescriptions/prescriptions_view_model.dart';
import 'package:hmg_patient_app_new/features/profile_settings/profile_settings_view_model.dart';
import 'package:hmg_patient_app_new/features/todo_section/todo_section_view_model.dart';
import 'package:hmg_patient_app_new/features/water_monitor/water_monitor_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/allergies/allergies_list_page.dart';
import 'package:hmg_patient_app_new/presentation/appointments/my_appointments_page.dart';
import 'package:hmg_patient_app_new/presentation/appointments/my_doctors_page.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/ask_doctor_request_type_select.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/book_appointment_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/doctor_profile_page.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/widgets/appointment_calendar.dart';
import 'package:hmg_patient_app_new/presentation/insurance/insurance_approvals_page.dart';
import 'package:hmg_patient_app_new/presentation/insurance/insurance_home_page.dart';
import 'package:hmg_patient_app_new/presentation/insurance/widgets/insurance_update_details_card.dart';
import 'package:hmg_patient_app_new/presentation/insurance/widgets/patient_insurance_card.dart';
import 'package:hmg_patient_app_new/presentation/lab/lab_orders_page.dart';
import 'package:hmg_patient_app_new/presentation/lab/lab_result_item_view.dart';
import 'package:hmg_patient_app_new/presentation/medical_file/eye_measurements_appointments_page.dart';
import 'package:hmg_patient_app_new/presentation/medical_file/patient_sickleaves_list_page.dart';
import 'package:hmg_patient_app_new/presentation/medical_file/vaccine_list_page.dart';
import 'package:hmg_patient_app_new/presentation/medical_file/widgets/health_tools_card.dart';
import 'package:hmg_patient_app_new/presentation/medical_file/widgets/lab_rad_card.dart';
import 'package:hmg_patient_app_new/presentation/medical_file/widgets/medical_file_card.dart';
import 'package:hmg_patient_app_new/presentation/medical_file/widgets/medical_report_card.dart';
import 'package:hmg_patient_app_new/presentation/medical_file/widgets/patient_sick_leave_card.dart';
import 'package:hmg_patient_app_new/presentation/my_family/my_family.dart';
import 'package:hmg_patient_app_new/presentation/my_invoices/my_invoices_list.dart';
import 'package:hmg_patient_app_new/presentation/prescriptions/prescriptions_list_page.dart';
import 'package:hmg_patient_app_new/presentation/radiology/radiology_orders_page.dart';
import 'package:hmg_patient_app_new/presentation/todo_section/todo_page.dart';
import 'package:hmg_patient_app_new/presentation/vital_sign/vital_sign_page.dart';
import 'package:hmg_patient_app_new/services/cache_service.dart';
import 'package:hmg_patient_app_new/services/navigation_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/expandable_list_widget.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:hmg_patient_app_new/widgets/shimmer/common_shimmer_widget.dart';
import 'package:hmg_patient_app_new/widgets/user_avatar_widget.dart';
import 'package:provider/provider.dart';

import '../../features/active_prescriptions/active_prescriptions_view_model.dart';
import '../prescriptions/prescription_detail_page.dart';
import 'widgets/medical_file_appointment_card.dart';

class MedicalFilePage extends StatefulWidget {
  bool showBackIcon;

  MedicalFilePage({super.key, this.showBackIcon = true});

  @override
  State<MedicalFilePage> createState() => _MedicalFilePageState();
}

class _MedicalFilePageState extends State<MedicalFilePage> {
  late InsuranceViewModel insuranceViewModel;
  late AppState appState;
  late MyAppointmentsViewModel myAppointmentsViewModel;
  late MedicalFileViewModel medicalFileViewModel;
  late BookAppointmentsViewModel bookAppointmentsViewModel;
  late LabViewModel labViewModel;
  late MyInvoicesViewModel myInvoicesViewModel;
  late HmgServicesViewModel hmgServicesViewModel;
  late PrescriptionsViewModel prescriptionsViewModel;
  late MonthlyReportViewModel monthlyReportViewModel;

  final CacheService cacheService = GetIt.instance<CacheService>();
  late ActivePrescriptionsViewModel activePrescriptionsViewModel;

  int currentIndex = 0;

  @override
  void initState() {
    appState = getIt.get<AppState>();
    scheduleMicrotask(() {
      if (appState.isAuthenticated) {
        insuranceViewModel.initInsuranceProvider();
        // Load vital signs
        hmgServicesViewModel.getPatientVitalSign();

        // myAppointmentsViewModel.getPatientMyDoctors(isTop8: true);
        // prescriptionsViewModel.initPrescriptionsViewModel();

        // medicalFileViewModel.setIsPatientSickLeaveListLoading(true);
        // medicalFileViewModel.getPatientSickLeaveList();
        // medicalFileViewModel.setIsPatientMedicalReportsLoading(true);
        // medicalFileViewModel.getPatientMedicalReportList();

        medicalFileViewModel.onTabChanged(0);
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    labViewModel = Provider.of<LabViewModel>(context, listen: false);
    insuranceViewModel = Provider.of<InsuranceViewModel>(context, listen: false);
    myAppointmentsViewModel = Provider.of<MyAppointmentsViewModel>(context, listen: false);
    medicalFileViewModel = Provider.of<MedicalFileViewModel>(context, listen: false);
    bookAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);
    myInvoicesViewModel = Provider.of<MyInvoicesViewModel>(context, listen: false);
    hmgServicesViewModel = Provider.of<HmgServicesViewModel>(context, listen: false);
    prescriptionsViewModel = Provider.of<PrescriptionsViewModel>(context, listen: false);
    monthlyReportViewModel = Provider.of<MonthlyReportViewModel>(context, listen: false);
    NavigationService navigationService = getIt.get<NavigationService>();
    return CollapsingListView(
      // title: "Medical File".needTranslation,
      title: LocaleKeys.medicalFile.tr(context: context),
      trailing: Row(
        children: [
          Wrap(
            spacing: -12.h,
            // runSpacing: 0.h,
            children: [
              Utils.buildImgWithAssets(
                icon: AppAssets.babyGirlImg,
                height: 32.h,
                width: 32.w,
                border: 1,
                fit: BoxFit.contain,
                borderRadius: 50.r,
              ),
              Utils.buildImgWithAssets(
                icon: AppAssets.femaleImg,
                height: 32.h,
                width: 32.w,
                border: 1,
                borderRadius: 50.r,
                fit: BoxFit.contain,
              ),
              Utils.buildImgWithAssets(
                icon: AppAssets.maleImg,
                height: 32.h,
                width: 32.w,
                border: 1.5,
                borderRadius: 50.r,
                fit: BoxFit.contain,
              ),
            ],
          ),
          SizedBox(width: 4.h),
          Transform.flip(flipX: appState.isArabic(), child: Utils.buildSvgWithAssets(icon: AppAssets.arrowRight, height: 22.h, width: 22.w))
        ],
      ).onPress(() {
        Navigator.of(context).push(
          CustomPageRoute(
            direction: AxisDirection.down,
            page: FamilyMedicalScreen(),
          ),
        );
        // DialogService dialogService = getIt.get<DialogService>();
        // dialogService.showFamilyBottomSheetWithoutH(
        //     label: LocaleKeys.familyTitle.tr(context: context),
        //     message: "",
        //     isShowManageButton: true,
        //     onSwitchPress: (FamilyFileResponseModelLists profile) {
        //       medicalFileViewModel.switchFamilyFiles(responseID: profile.responseId, patientID: profile.patientId, phoneNumber: profile.mobileNumber);
        //     },
        //     profiles: medicalFileViewModel.patientFamilyFiles);
      }),
      isLeading: widget.showBackIcon,
      // leadingCallback: () {
      //   Navigator.pushAndRemoveUntil(
      //       navigationService.navigatorKey.currentContext!,
      //       CustomPageRoute(
      //         page: LandingNavigation(),
      //       ),
      //       (r) => false);
      // },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 16.h),
          Container(
            width: double.infinity,
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 12.r),
            child: Padding(
              padding: EdgeInsets.all(16.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Selector<ProfileSettingsViewModel, String?>(
                        selector: (_, profileVM) => profileVM.profileImageData ?? appState.getProfileImageData,
                        shouldRebuild: (previous, next) => previous != next,
                        builder: (context, profileImageData, child) {
                          return UserAvatarWidget(
                            key: ValueKey('medical_avatar_${profileImageData?.hashCode ?? 0}'),
                            width: 56.h,
                            height: 56.h,
                            fit: BoxFit.cover,
                            isCircular: true,
                            customProfileImageData: profileImageData,
                          );
                        },
                      ),
                      SizedBox(width: 8.w),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(
                            width: MediaQuery.of(context).size.width * 0.6,
                            child:
                                "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}".toText18(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 2),
                          ),
                          SizedBox(height: 4.h),
                          Wrap(
                            direction: Axis.horizontal,
                            spacing: 4.w,
                            runSpacing: 6.w,
                            children: [
                              AppCustomChipWidget(
                                icon: AppAssets.file_icon,
                                labelText: "${LocaleKeys.fileno.tr(context: context)}: ${appState.getAuthenticatedUser()!.patientId}",
                                labelPadding: EdgeInsetsDirectional.only(start: -4.w, end: 6.w),
                              ),
                              AppCustomChipWidget(
                                icon: AppAssets.checkmark_icon,
                                labelText: LocaleKeys.verified.tr(context: context),
                                iconColor: AppColors.successColor,
                                labelPadding: EdgeInsetsDirectional.only(start: -4.w, end: 6.w),
                              ),
                            ],
                          ),
                        ],
                      )
                    ],
                  ),
                  SizedBox(height: 16.h),
                  Divider(color: AppColors.dividerColor, height: 1.h),
                  SizedBox(height: 16.h),
                  Wrap(
                    direction: Axis.horizontal,
                    spacing: 4.h,
                    runSpacing: 4.h,
                    children: [
                      AppCustomChipWidget(
                        labelText: LocaleKeys.ageYearsOld.tr(namedArgs: {'age': '${appState.getAuthenticatedUser()!.age}', 'yearsOld': LocaleKeys.yearsOld.tr(context: context)}, context: context),
                        labelPadding: EdgeInsetsDirectional.only(start: 8.w, end: 8.w),
                      ),
                      AppCustomChipWidget(
                        icon: AppAssets.blood_icon,
                        labelText: appState.getUserBloodGroup.isEmpty ? "N/A" : appState.getUserBloodGroup,
                        iconColor: AppColors.primaryRedColor,
                        labelPadding: EdgeInsetsDirectional.only(start: -6.w, end: 6.w),
                        padding: EdgeInsets.zero,
                      ),
                      Consumer<InsuranceViewModel>(builder: (context, insuranceVM, child) {
                        return AppCustomChipWidget(
                          icon: insuranceVM.isInsuranceExpired
                              ? AppAssets.cancel_circle_icon
                              : insuranceVM.isInsuranceActive
                                  ? AppAssets.insurance_active_icon
                                  : AppAssets.alertSquare,
                          labelText: insuranceVM.isInsuranceExpired
                              ? LocaleKeys.insuranceExpired.tr(context: context)
                              : insuranceVM.isInsuranceActive
                                  ? LocaleKeys.insuranceActive.tr(context: context)
                                  : LocaleKeys.insuranceInActive.tr(context: context),
                          iconColor: insuranceVM.isInsuranceExpired
                              ? AppColors.primaryRedColor
                              : insuranceVM.isInsuranceActive
                                  ? AppColors.successColor
                                  : AppColors.warningColorYellow,
                          textColor: insuranceVM.isInsuranceExpired
                              ? AppColors.primaryRedColor
                              : insuranceVM.isInsuranceActive
                                  ? AppColors.successColor
                                  : AppColors.warningColorYellow,
                          iconSize: 12.w,
                          deleteIcon: insuranceVM.isInsuranceActive ? null : AppAssets.forward_chevron_icon,
                          deleteIconColor: insuranceVM.isInsuranceExpired
                              ? AppColors.primaryRedColor
                              : insuranceVM.isInsuranceActive
                                  ? AppColors.successColor
                                  : AppColors.warningColorYellow,
                          deleteIconHasColor: true,
                          onChipTap: () {
                            if (!insuranceVM.isInsuranceActive) {
                              insuranceVM.setIsInsuranceUpdateDetailsLoading(true);
                              insuranceVM.getPatientInsuranceDetailsForUpdate(
                                  appState.getAuthenticatedUser()!.patientId.toString(), appState.getAuthenticatedUser()!.patientIdentificationNo.toString());
                              showCommonBottomSheetWithoutHeight(context, child: PatientInsuranceCardUpdateCard(), callBackFunc: () {}, title: "", isCloseButtonVisible: false, isFullScreen: false);
                              // showCommonBottomSheetWithoutHeight(
                              //   title: LocaleKeys.notice.tr(context: navigationService.navigatorKey.currentContext!),
                              //   navigationService.navigatorKey.currentContext!,
                              //   child: Utils.getWarningWidget(
                              //       loadingText: LocaleKeys.insuranceInActiveContactSupport.tr(context: context),
                              //       confirmText: LocaleKeys.contactUs.tr(context: context),
                              //       isShowActionButtons: true,
                              //       onCancelTap: () {
                              //         navigationService.pop();
                              //       },
                              //       onConfirmTap: () async {
                              //         launchUrl(Uri.parse("tel://" + "+966 92 006 6666"));
                              //       }),
                              //   callBackFunc: () {},
                              //   isFullScreen: false,
                              //   isCloseButtonVisible: true,
                              // );
                            }
                          },
                          backgroundColor: insuranceVM.isInsuranceExpired
                              ? AppColors.primaryRedColor.withOpacity(0.1)
                              : insuranceVM.isInsuranceActive
                                  ? AppColors.successColor.withOpacity(0.1)
                                  : AppColors.warningColorYellow.withOpacity(0.1),
                          labelPadding: EdgeInsetsDirectional.only(start: -4.w, end: insuranceVM.isInsuranceActive ? 6.w : 0.w),
                        ).toShimmer2(isShow: insuranceVM.isInsuranceLoading);
                      }),
                    ],
                  ),
                ],
              ),
            ),
          ).paddingSymmetrical(24.w, 0.0),
          SizedBox(height: 16.h),

          // Vital Signs Section
          Consumer<HmgServicesViewModel>(builder: (context, hmgServicesVM, child) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 24.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      LocaleKeys.vitalSigns.tr(context: context).toText16(isBold: true, letterSpacing: -0.2),
                      Row(
                        children: [
                          LocaleKeys.viewAll.tr(context: context).toText12(color: AppColors.primaryRedColor, isBold: true),
                          SizedBox(width: 2.h),
                          Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h),
                        ],
                      ),
                    ],
                  ).paddingSymmetrical(0.w, 0.h).onPress(() {
                    Navigator.of(context).push(
                      CustomPageRoute(
                        page: VitalSignPage(),
                      ),
                    );
                  }),
                ),
                SizedBox(height: 16.h),
                // Make this section dynamic-height (no fixed 160.h)
                LayoutBuilder(
                  builder: (context, constraints) {
                    if (hmgServicesVM.isVitalSignLoading) {
                      return Padding(
                        padding: EdgeInsets.symmetric(horizontal: 24.w),
                        child: _buildVitalSignShimmer(),
                      );
                    }
                    if (hmgServicesVM.vitalSignList.isEmpty) {
                      return Padding(
                        padding: EdgeInsets.symmetric(horizontal: 24.w),
                        child: Container(
                          padding: EdgeInsets.all(16.w),
                          width: MediaQuery.of(context).size.width,
                          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                            color: AppColors.whiteColor,
                            borderRadius: 12.r,
                            hasShadow: false,
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Utils.buildSvgWithAssets(icon: AppAssets.call_for_vitals, width: 32.h, height: 32.h),
                              SizedBox(height: 12.h),
                              LocaleKeys.noVitalSignsRecordedYet.tr(context: context).toText12(isCenter: true),
                            ],
                          ),
                        ),
                      );
                    }

                    // Responsive PageView with dynamic height constraint
                    return ConstrainedBox(
                      constraints: BoxConstraints(
                        minHeight: 135.h,
                        maxHeight: 150.h,
                        // maxHeight: isFoldable ? 150.h : (isTablet ? 140.h : 140.h),
                      ),
                      child: PageView(
                        controller: hmgServicesVM.vitalSignPageController,
                        onPageChanged: (index) {
                          hmgServicesVM.setVitalSignCurrentPage(index);
                        },
                        children: _buildVitalSignPages(
                          vitalSign: hmgServicesVM.vitalSignList.first,
                          onTap: () {
                            Navigator.of(context).push(
                              CustomPageRoute(
                                page: VitalSignPage(),
                              ),
                            );
                          },
                          currentPageIndex: hmgServicesVM.vitalSignCurrentPage,
                        ),
                      ),
                    );
                  },
                ),
                if (!hmgServicesVM.isVitalSignLoading && hmgServicesVM.vitalSignList.isNotEmpty) ...[
                  SizedBox(height: 12.h),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: List.generate(
                      2, // 2 pages (BMI+Height on page 1, Weight+BP on page 2)
                      (index) => Container(
                        margin: EdgeInsets.symmetric(horizontal: 3.w),
                        width: hmgServicesVM.vitalSignCurrentPage == index ? 24.w : 8.w,
                        height: 8.h,
                        decoration: BoxDecoration(
                          color: hmgServicesVM.vitalSignCurrentPage == index ? AppColors.primaryRedColor : AppColors.dividerColor,
                          borderRadius: BorderRadius.circular(4.r),
                        ),
                      ),
                    ),
                  ),
                ],
              ],
            );
          }),
          SizedBox(height: 24.h),
          // TextInputWidget(
          //   labelText: LocaleKeys.search.tr(context: context),
          //   hintText: "Type any record".needTranslation,
          //   controller: TextEditingController(),
          //   keyboardType: TextInputType.number,
          //   isEnable: true,
          //   prefix: null,
          //   autoFocus: false,
          //   isBorderAllowed: false,
          //   isAllowLeadingIcon: true,
          //   padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 8.h),
          //   leadingIcon: AppAssets.search_icon,
          //   hintColor: AppColors.textColor,
          // ).paddingSymmetrical(24.w, 0.0),
          // SizedBox(height: 16.h),
          // Using CustomExpandableList
          CustomExpandableList(
            expansionMode: ExpansionMode.exactlyOne,
            dividerColor: AppColors.dividerColor,
            itemPadding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 14.h),
            onItemToggled: (index, isExpanded) {
              debugPrint("Item at index $index is now ${isExpanded ? 'expanded' : 'collapsed'}");

              if (index == 0 && isExpanded) {
                myAppointmentsViewModel.getPatientMyDoctors(isTop8: true);
                prescriptionsViewModel.initPrescriptionsViewModel();
              }
              if (index == 1 && isExpanded) {
                medicalFileViewModel.setIsPatientSickLeaveListLoading(true);
                medicalFileViewModel.getPatientSickLeaveList();
                medicalFileViewModel.setIsPatientMedicalReportsLoading(true);
                medicalFileViewModel.getPatientMedicalReportList();
              }
            },
            items: [
              ExpandableListItem(
                title: LocaleKeys.medicalServices.tr(context: context).toText18(isBold: true),
                expandedBackgroundColor: Colors.transparent,
                children: [
                  SizedBox(height: 10.h),
                  getSelectedTabData(0),
                ],
              ),
              ExpandableListItem(title: LocaleKeys.medicalReports.tr(context: context).toText18(isBold: true), expandedBackgroundColor: Colors.transparent, children: [
                SizedBox(height: 10.h),
                getSelectedTabData(2),
              ]),
              ExpandableListItem(
                title: LocaleKeys.insuranceAndPayments.tr(context: context).toText18(isBold: true),
                expandedBackgroundColor: Colors.transparent,
                children: [
                  SizedBox(height: 10.h),
                  getSelectedTabData(1),
                ],
              ),
              ExpandableListItem(
                title: LocaleKeys.healthTools.tr(context: context).toText18(isBold: true),
                expandedBackgroundColor: Colors.transparent,
                children: [
                  SizedBox(height: 10.h),
                  getSelectedTabData(3),
                ],
              ),
            ],
            theme: ExpandableListTheme.custom(
              defaultTrailingIcon: Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, height: 22.h, width: 22.w, iconColor: AppColors.textColor),
            ),
          ).paddingSymmetrical(16.w, 0.0),
        ],
      ),
    );
  }

  openDoctorScheduleCalendar(PatientAppointmentHistoryResponseModel patientAppointmentHistoryResponseModel) async {
    DoctorsListResponseModel doctor = DoctorsListResponseModel(
      clinicID: patientAppointmentHistoryResponseModel.clinicID,
      projectID: patientAppointmentHistoryResponseModel.projectID,
      doctorID: patientAppointmentHistoryResponseModel.doctorID,
      doctorImageURL: patientAppointmentHistoryResponseModel.doctorImageURL,
      doctorTitle: patientAppointmentHistoryResponseModel.doctorTitle,
      name: patientAppointmentHistoryResponseModel.doctorNameObj,
      nationalityFlagURL: "",
      speciality: [],
      clinicName: patientAppointmentHistoryResponseModel.clinicName,
      projectName: patientAppointmentHistoryResponseModel.projectName,
    );
    bookAppointmentsViewModel.setSelectedDoctor(doctor);
    LoaderBottomSheet.showLoader();
    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,
          );
        });
  }

  Widget buildInsuranceTab(int index) {
    return Column(
      children: [
        Consumer<InsuranceViewModel>(builder: (context, insuranceVM, child) {
          return insuranceVM.isInsuranceLoading
              ? LabResultItemView(
                  onTap: () {},
                  labOrder: null,
                  index: index,
                  isLoading: true,
                ).paddingSymmetrical(0.w, 0.0)
              : insuranceVM.patientInsuranceList.isNotEmpty
                  ? PatientInsuranceCard(
                      insuranceCardDetailsModel: insuranceVM.patientInsuranceList.first,
                      isInsuranceExpired: DateTime.now().isAfter(
                        DateUtil.convertStringToDate(insuranceVM.patientInsuranceList.first.cardValidTo),
                      ),
                    )
                  : Container(
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                        // color: AppColors.bgRedLightColor,
                        borderRadius: 12.r,
                        hasShadow: false,
                      ),
                      child: Utils.getNoDataWidget(
                        context,
                        noDataText: LocaleKeys.noInsuranceWithHMG.tr(context: context),
                        isSmallWidget: true,
                        width: 62.w,
                        height: 62.h,
                        callToActionButton: CustomButton(
                          icon: AppAssets.update_insurance_card_icon,
                          iconColor: AppColors.successColor,
                          iconSize: 15.h,
                          text: "${LocaleKeys.updateInsurance.tr(context: context)} ${LocaleKeys.updateInsuranceSubtitle.tr(context: context)}",
                          onPressed: () {
                            insuranceViewModel.setIsInsuranceUpdateDetailsLoading(true);
                            insuranceViewModel.getPatientInsuranceDetailsForUpdate(
                                appState.getAuthenticatedUser()!.patientId.toString(), appState.getAuthenticatedUser()!.patientIdentificationNo.toString());
                            showCommonBottomSheetWithoutHeight(context, child: PatientInsuranceCardUpdateCard(), callBackFunc: () {}, title: "", isCloseButtonVisible: false, isFullScreen: false);
                          },
                          backgroundColor: AppColors.bgGreenColor.withOpacity(0.20),
                          borderColor: AppColors.bgGreenColor.withOpacity(0.0),
                          textColor: AppColors.bgGreenColor,
                          fontSize: 14.f,
                          fontWeight: FontWeight.w600,
                          borderRadius: 12.r,
                          padding: EdgeInsets.fromLTRB(10.w, 0, 10.w, 0),
                          height: isFoldable ? 50.h : 40.h,
                        ).paddingOnly(left: 12.w, right: 12.w, bottom: 12.h),
                      ),
                    ).paddingSymmetrical(0.w, 0.h);
        }),
        SizedBox(height: 10.h),
        GridView(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 10.h,
            mainAxisSpacing: 16.w,
            childAspectRatio: isFoldable ? 1.2 : (isTablet ? 1.4 : 0.98),
            // mainAxisExtent: 120.h,
          ),
          physics: NeverScrollableScrollPhysics(),
          padding: EdgeInsets.only(top: 12.h),
          shrinkWrap: true,
          children: [
            MedicalFileCard(
              label: LocaleKeys.updateInsuranceInfo.tr(context: context),
              textColor: AppColors.blackColor,
              backgroundColor: AppColors.whiteColor,
              svgIcon: AppAssets.update_insurance_icon,
              isLargeText: true,
              iconSize: 36.w,
            ).onPress(() {
              Navigator.of(context).push(CustomPageRoute(page: InsuranceHomePage()));
            }),
            MedicalFileCard(
              label: "${LocaleKeys.approvals1.tr(context: context)} ${LocaleKeys.insurance.tr(context: context)}",
              textColor: AppColors.blackColor,
              backgroundColor: AppColors.whiteColor,
              svgIcon: AppAssets.insurance_approval_icon,
              isLargeText: true,
              iconSize: 36.w,
            ).onPress(() {
              Navigator.of(context).push(CustomPageRoute(page: InsuranceApprovalsPage()));
            }),
            MedicalFileCard(
              label: LocaleKeys.myInvoicesList.tr(context: context),
              textColor: AppColors.blackColor,
              backgroundColor: AppColors.whiteColor,
              svgIcon: AppAssets.invoices_list_icon,
              isLargeText: true,
              iconSize: 36.w,
            ).onPress(() {
              Navigator.of(context).push(CustomPageRoute(page: MyInvoicesList()));
            }),
            // MedicalFileCard(
            //   label: LocaleKeys.requestRefund.tr(context: context),
            //   textColor: AppColors.blackColor,
            //   backgroundColor: AppColors.whiteColor,
            //   svgIcon: AppAssets.ancillary_orders_list_icon,
            //   isLargeText: true,
            //   iconSize: 36.w,
            // ).onPress(() {
            //   Navigator.of(context).push(
            //     CustomPageRoute(
            //       page: const RefundRequestCreatePage(initialTabIndex: 0),
            //     ),
            //   );
            // }),
            MedicalFileCard(
              label: LocaleKeys.ancillaryOrdersListNew.tr(context: context),
              textColor: AppColors.blackColor,
              backgroundColor: AppColors.whiteColor,
              svgIcon: AppAssets.ancillary_orders_list_icon,
              isLargeText: true,
              iconSize: 36.w,
            ).onPress(() {
              getIt.get<TodoSectionViewModel>().setIsAncillaryOrdersNeedReloading(true);
              Navigator.of(context).push(
                CustomPageRoute(
                  page: ToDoPage(),
                ),
              );
            }),
          ],
        ).paddingSymmetrical(0.w, 0.0),
        SizedBox(height: 16.h),
      ],
    );
  }

  Widget buildMedicalServicesTab() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            LocaleKeys.appointmentsAndVisits.tr(context: context).toText16(isBold: true, letterSpacing: -0.2),
            Row(
              children: [
                LocaleKeys.viewAll.tr(context: context).toText12(color: AppColors.primaryRedColor, isBold: true),
                SizedBox(width: 2.h),
                Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h),
              ],
            ),
          ],
        ).paddingSymmetrical(0.w, 0.h).onPress(() {
          Navigator.of(context).push(CustomPageRoute(page: MyAppointmentsPage()));
        }),
        SizedBox(height: 16.h),
        Consumer<MyAppointmentsViewModel>(builder: (context, myAppointmentsVM, child) {
          // Dynamic height that adapts to device and content
          return ConstrainedBox(
            constraints: BoxConstraints(
              minHeight: 150.h,
              maxHeight: isFoldable ? 210.h : (isTablet ? 200.h : 180.h),
            ),
            child: myAppointmentsVM.isMyAppointmentsLoading
                ? MedicalFileAppointmentCard(
                    patientAppointmentHistoryResponseModel: PatientAppointmentHistoryResponseModel(),
                    myAppointmentsViewModel: myAppointmentsVM,
                    onRescheduleTap: () {},
                    onAskDoctorTap: () {},
                  )
                : myAppointmentsVM.patientAppointmentsHistoryList.isEmpty
                    ? Container(
                        padding: EdgeInsets.all(12.w),
                        width: MediaQuery.of(context).size.width,
                        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 12.r, hasShadow: false),
                        child: Column(
                          children: [
                            Utils.buildSvgWithAssets(icon: AppAssets.home_calendar_icon, width: 32.h, height: 32.h),
                            SizedBox(height: 12.h),
                            LocaleKeys.noUpcomingAppointmentPleaseBook.tr(context: context).toText12(isCenter: true),
                            SizedBox(height: 12.h),
                            CustomButton(
                              text: LocaleKeys.bookAppo.tr(context: context),
                              onPressed: () {
                                getIt.get<BookAppointmentsViewModel>().onTabChanged(0);
                                Navigator.of(context).push(
                                  CustomPageRoute(
                                    page: BookAppointmentPage(),
                                  ),
                                );
                              },
                              backgroundColor: AppColors.secondaryLightRedColor,
                              borderColor: AppColors.secondaryLightRedColor,
                              textColor: AppColors.primaryRedColor,
                              fontSize: 14.f,
                              fontWeight: FontWeight.w600,
                              borderRadius: 12.r,
                              padding: EdgeInsets.symmetric(horizontal: 10.w),
                              height: isFoldable || isTablet ? 50.h : 40.h,
                              icon: AppAssets.add_icon,
                              iconColor: AppColors.primaryRedColor,
                            ),
                          ],
                        ),
                      )
                    : ListView.separated(
                        scrollDirection: Axis.horizontal,
                        shrinkWrap: true,
                        itemCount: myAppointmentsVM.patientAppointmentsHistoryList.length,
                        padding: EdgeInsets.zero,
                        itemBuilder: (context, index) {
                          return AnimationConfiguration.staggeredList(
                              position: index,
                              duration: const Duration(milliseconds: 500),
                              child: SlideAnimation(
                                horizontalOffset: 100.0,
                                child: FadeInAnimation(
                                  child: AnimatedContainer(
                                    duration: const Duration(milliseconds: 300),
                                    curve: Curves.easeInOut,
                                    child: MedicalFileAppointmentCard(
                                      patientAppointmentHistoryResponseModel: myAppointmentsVM.patientAppointmentsHistoryList[index],
                                      myAppointmentsViewModel: myAppointmentsViewModel,
                                      onRescheduleTap: () {
                                        openDoctorScheduleCalendar(myAppointmentsVM.patientAppointmentsHistoryList[index]);
                                      },
                                      onAskDoctorTap: () async {
                                        LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingDoctorAvailability.tr(context: context));
                                        await myAppointmentsViewModel.isDoctorAvailable(
                                          projectID: myAppointmentsVM.patientAppointmentsHistoryList[index].projectID,
                                          doctorId: myAppointmentsVM.patientAppointmentsHistoryList[index].doctorID,
                                          clinicId: myAppointmentsVM.patientAppointmentsHistoryList[index].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: myAppointmentsVM.patientAppointmentsHistoryList[index],
                                                  ),
                                                  callBackFunc: () {},
                                                  isFullScreen: false,
                                                  isCloseButtonVisible: true,
                                                );
                                              });
                                            } else {
                                              LoaderBottomSheet.hideLoader();
                                            }
                                          },
                                          onError: (_) {
                                            LoaderBottomSheet.hideLoader();
                                          },
                                        );
                                      },
                                    ),
                                  ),
                                ),
                              ));
                        },
                        separatorBuilder: (BuildContext cxt, int index) => SizedBox(width: 12.w),
                      ),
          );
        }),
        SizedBox(height: 10.h),
        LocaleKeys.labAndRadiology.tr(context: context).toText16(isBold: true, letterSpacing: -0.2),
        SizedBox(height: 16.h),
        Row(
          children: [
            Expanded(
              child: LabRadCard(
                icon: AppAssets.lab_result_icon,
                labelText: LocaleKeys.labResults.tr(context: context),
                // labOrderTests: ["Complete blood count", "Creatinine", "Blood Sugar"],
                labOrderTests: labViewModel.isLabOrdersLoading ? [] : labViewModel.labOrderTests,
                isLoading: labViewModel.isLabOrdersLoading,
              ).onPress(() {
                Navigator.of(context).push(
                  CustomPageRoute(
                    page: LabOrdersPage(),
                  ),
                );
              }),
            ),
            SizedBox(width: 8.w),
            Expanded(
              child: LabRadCard(
                icon: AppAssets.radiology_icon,
                labelText: LocaleKeys.radiologyLabResults.tr(context: context),
                // labOrderTests: ["Complete blood count", "Creatinine", "Blood Sugar",
                // labOrderTests: ["Chest X-ray", "Abdominal Ultrasound", "Dental X-ray"],
                labOrderTests: [],
                isLoading: false,
              ).onPress(() {
                Navigator.of(context).push(
                  CustomPageRoute(
                    page: RadiologyOrdersPage(),
                  ),
                );
              }),
            ),
          ],
        ).paddingSymmetrical(0.w, 0.h),
        SizedBox(height: 24.h),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            LocaleKeys.activeMedicationsAndPrescriptions.tr(context: context).toText16(isBold: true, letterSpacing: -0.2),
            Row(
              children: [
                LocaleKeys.viewAll.tr(context: context).toText12(color: AppColors.primaryRedColor, isBold: true),
                SizedBox(width: 2.w),
                Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h),
              ],
            ).onPress(() {
              // myAppointmentsViewModel.getPatientMyDoctors();
              Navigator.of(context).push(
                CustomPageRoute(
                  page: PrescriptionsListPage(),
                ),
              );
            }),
          ],
        ),
        SizedBox(height: 16.h),
        Consumer<PrescriptionsViewModel>(builder: (context, prescriptionVM, child) {
          return prescriptionVM.isPrescriptionsOrdersLoading
              ? const CommonShimmerWidget().paddingSymmetrical(0.w, 0.h)
              : prescriptionVM.patientPrescriptionOrders.isNotEmpty
                  ? Container(
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 20.r, hasShadow: false),
                      child: Padding(
                        padding: EdgeInsets.all(16.w),
                        child: Column(
                          children: [
                            ListView.separated(
                              itemCount: prescriptionVM.patientPrescriptionOrders.length <= 2 ? prescriptionVM.patientPrescriptionOrders.length : 2,
                              shrinkWrap: true,
                              padding: EdgeInsets.only(left: 0, right: 8.w),
                              physics: NeverScrollableScrollPhysics(),
                              itemBuilder: (context, index) {
                                return AnimationConfiguration.staggeredList(
                                    position: index,
                                    duration: const Duration(milliseconds: 500),
                                    child: SlideAnimation(
                                      verticalOffset: 100.0,
                                      child: FadeInAnimation(
                                        child: Row(
                                          children: [
                                            Utils.buildImgWithNetwork(
                                              url: prescriptionVM.patientPrescriptionOrders[index].doctorImageURL!,
                                              iconColor: AppColors.transparent,
                                              width: 40.h,
                                              height: 40.h,
                                              fit: BoxFit.cover,
                                            ).circle(100.r),
                                            SizedBox(width: 16.w),
                                            Expanded(
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: [
                                                  prescriptionVM.patientPrescriptionOrders[index].doctorName!.toText16(isBold: true),
                                                  SizedBox(height: 4.h),
                                                  Wrap(
                                                    direction: Axis.horizontal,
                                                    spacing: 3.w,
                                                    runSpacing: 4.w,
                                                    children: [
                                                      AppCustomChipWidget(labelText: prescriptionVM.patientPrescriptionOrders[index].clinicDescription!),
                                                      Directionality(
                                                        textDirection: ui.TextDirection.ltr,
                                                        child: AppCustomChipWidget(
                                                          icon: AppAssets.doctor_calendar_icon,
                                                          labelText: DateUtil.formatDateToDate(
                                                            DateUtil.convertStringToDate(prescriptionVM.patientPrescriptionOrders[index].appointmentDate),
                                                            false,
                                                          ),
                                                          isEnglishOnly: true,
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                ],
                                              ),
                                            ),
                                            // SizedBox(width: 40.h),
                                            Transform.flip(
                                                flipX: appState.isArabic(),
                                                child:
                                                    Utils.buildSvgWithAssets(icon: AppAssets.forward_arrow_icon_small, width: 15.w, height: 15.h, fit: BoxFit.contain, iconColor: AppColors.textColor)),
                                          ],
                                        ).onPress(() {
                                          prescriptionVM.setPrescriptionsDetailsLoading();
                                          Navigator.of(context).push(
                                            CustomPageRoute(
                                              page: PrescriptionDetailPage(isFromAppointments: false, prescriptionsResponseModel: prescriptionVM.patientPrescriptionOrders[index]),
                                            ),
                                          );
                                        }),
                                      ),
                                    ));
                              },
                              separatorBuilder: (BuildContext cxt, int index) => SizedBox(height: 16.h),
                            ),
                            SizedBox(height: 16.h),
                            // Divider(color: AppColors.dividerColor),
                            // SizedBox(height: 16.h),
                            // Row(
                            //   children: [
                            //     Expanded(
                            //       child: CustomButton(
                            //         text: LocaleKeys.allPrescriptions.tr(context: context),
                            //         onPressed: () {
                            //           Navigator.of(context).push(
                            //             CustomPageRoute(
                            //               page: PrescriptionsListPage(),
                            //             ),
                            //           );
                            //         },
                            //         backgroundColor: AppColors.secondaryLightRedColor,
                            //         borderColor: AppColors.secondaryLightRedColor,
                            //         textColor: AppColors.primaryRedColor,
                            //         fontSize: 12.f,
                            //         isBold: true,
                            //         borderRadius: 12.r,
                            //         height: 40.h,
                            //         icon: AppAssets.requests,
                            //         iconColor: AppColors.primaryRedColor,
                            //         iconSize: 16.w,
                            //       ),
                            //     ),
                            //     SizedBox(width: 6.w),
                            //     Expanded(
                            //       child: CustomButton(
                            //         text: LocaleKeys.allMedications.tr(context: context),
                            //         onPressed: () {  Navigator.of(context).push(
                            //           CustomPageRoute(
                            //             page: ActiveMedicationPage(),
                            //           ),
                            //         );},
                            //         backgroundColor: AppColors.secondaryLightRedColor,
                            //         borderColor: AppColors.secondaryLightRedColor,
                            //         textColor: AppColors.primaryRedColor,
                            //         fontSize: 12.f,
                            //         isBold: true,
                            //         borderRadius: 12.h,
                            //         height: 40.h,
                            //         icon: AppAssets.all_medications_icon,
                            //         iconColor: AppColors.primaryRedColor,
                            //         iconSize: 16.h,
                            //       ),
                            //     ),
                            //   ],
                            // ),
                          ],
                        ),
                      ),
                    ).paddingSymmetrical(0.w, 0.h)
                  : Container(
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                        color: AppColors.whiteColor,
                        borderRadius: 12.r,
                        hasShadow: false,
                      ),
                      child: Utils.getNoDataWidget(
                        context,
                        noDataText: LocaleKeys.youDontHaveAnyPrescriptionsYet.tr(context: context),
                        isSmallWidget: true,
                        width: 62.w,
                        height: 62.h,
                      ),
                    ).paddingSymmetrical(0.w, 0.h);
        }),
        SizedBox(height: 24.h),
        //My Doctor Section
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            LocaleKeys.myDoctor.tr(context: context).toText16(isBold: true, letterSpacing: -0.2),
            Row(
              children: [
                LocaleKeys.viewAll.tr(context: context).toText12(color: AppColors.primaryRedColor, isBold: true),
                SizedBox(width: 2.w),
                Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h),
              ],
            ).onPress(() {
              // myAppointmentsViewModel.getPatientMyDoctors();
              // myAppointmentsViewModel.setIsMyDoctorsDataToBeLoaded(true);
              Navigator.of(context).push(
                CustomPageRoute(
                  page: MyDoctorsPage(),
                ),
              );
            }),
          ],
        ).paddingSymmetrical(0.w, 0.h),
        SizedBox(height: 16.h),
        Consumer<MyAppointmentsViewModel>(builder: (context, myAppointmentsVM, child) {
          return myAppointmentsVM.isPatientMyDoctorsLoading
              ? Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Utils.buildImgWithNetwork(
                      url: "https://hmgwebservices.com/Images/MobileImages/DUBAI/unkown_female.png",
                      iconColor: AppColors.transparent,
                      width: 64.h,
                      height: 64.h,
                      fit: BoxFit.cover,
                    ).circle(100).toShimmer2(isShow: true, radius: 50.r),
                    SizedBox(height: 8.h),
                    ("Dr. John Smith Smith Smith").toString().toText12(isBold: true, isCenter: true, maxLine: 2).toShimmer2(isShow: true),
                  ],
                )
              : myAppointmentsVM.patientMyDoctorsList.isEmpty
                  ? Container(
                      width: SizeConfig.screenWidth,
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                        color: AppColors.whiteColor,
                        borderRadius: 12.r,
                        hasShadow: false,
                      ),
                      child: Utils.getNoDataWidget(
                        context,
                        noDataText: LocaleKeys.youDontHaveAnyCompletedVisitsYet.tr(context: context),
                        isSmallWidget: true,
                        width: 62.w,
                        height: 62.h,
                      ),
                    ).paddingSymmetrical(0.w, 0.h)
                  : ConstrainedBox(
                      constraints: BoxConstraints(
                        minHeight: 100.h,
                        maxHeight: isFoldable ? 130.h : (isTablet ? 140.h : 115.h),
                      ),
                      child: ListView.separated(
                        scrollDirection: Axis.horizontal,
                        itemCount: myAppointmentsVM.patientMyDoctorsList.length,
                        shrinkWrap: true,
                        itemBuilder: (context, index) {
                          return AnimationConfiguration.staggeredList(
                              position: index,
                              duration: const Duration(milliseconds: 250),
                              child: SlideAnimation(
                                horizontalOffset: 100.0,
                                child: FadeInAnimation(
                                  child: SizedBox(
                                    // width: 80.w,
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.center,
                                      children: [
                                        Utils.buildImgWithNetwork(
                                          url: myAppointmentsVM.patientMyDoctorsList[index].doctorImageURL!,
                                          iconColor: AppColors.transparent,
                                          width: 64.h,
                                          height: 64.h,
                                          fit: BoxFit.cover,
                                        ).circle(100).toShimmer2(isShow: false, radius: 50.r),
                                        SizedBox(height: 8.h),
                                        SizedBox(
                                          width: 80.w,
                                          child: (myAppointmentsVM.patientMyDoctorsList[index].doctorName).toString().toText12(isBold: true, isCenter: true, maxLine: 2).toShimmer2(isShow: false),
                                        ),
                                      ],
                                    ),
                                  ).onPress(() async {
                                    bookAppointmentsViewModel.setSelectedDoctor(DoctorsListResponseModel(
                                      clinicID: myAppointmentsVM.patientMyDoctorsList[index].clinicID,
                                      projectID: myAppointmentsVM.patientMyDoctorsList[index].projectID,
                                      doctorID: myAppointmentsVM.patientMyDoctorsList[index].doctorID,
                                    ));
                                    LoaderBottomSheet.showLoader();
                                    await bookAppointmentsViewModel.getDoctorProfile(onSuccess: (dynamic respData) {
                                      LoaderBottomSheet.hideLoader();
                                      Navigator.of(context).push(
                                        CustomPageRoute(
                                          page: DoctorProfilePage(isDoctorAllowedToBook: !(myAppointmentsVM.patientMyDoctorsList[index].isLiveCareClinic ?? false)),
                                        ),
                                      );
                                    }, onError: (err) {
                                      LoaderBottomSheet.hideLoader();
                                      showCommonBottomSheetWithoutHeight(
                                        context,
                                        child: Utils.getErrorWidget(loadingText: err),
                                        callBackFunc: () {},
                                        isFullScreen: false,
                                        isCloseButtonVisible: true,
                                      );
                                    });
                                  }),
                                ),
                              ));
                        },
                        separatorBuilder: (BuildContext cxt, int index) => SizedBox(width: 8.h),
                      ),
                    ).paddingSymmetrical(0.w, 0);
        }),
        SizedBox(height: 24.h),
        LocaleKeys.others.tr(context: context).toText16(isBold: true, letterSpacing: -0.2),
        SizedBox(height: 16.h),
        GridView(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            childAspectRatio: isFoldable ? 1.2 : (isTablet ? 1.4 : 0.98),
            crossAxisSpacing: 10.h,
          ),
          physics: NeverScrollableScrollPhysics(),
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          children: [
            MedicalFileCard(
              label: LocaleKeys.eyeMeasurements.tr(context: context),
              textColor: AppColors.blackColor,
              backgroundColor: AppColors.whiteColor,
              svgIcon: AppAssets.eye_result_icon,
              isLargeText: true,
              iconSize: 36.w,
            ).onPress(() {
              myAppointmentsViewModel.setIsEyeMeasurementsAppointmentsLoading(true);
              myAppointmentsViewModel.onEyeMeasurementsTabChanged(0);
              myAppointmentsViewModel.getPatientEyeMeasurementAppointments();
              Navigator.of(context).push(
                CustomPageRoute(
                  page: EyeMeasurementsAppointmentsPage(),
                ),
              );
            }),
            MedicalFileCard(
              label: LocaleKeys.illurgyInfomation.tr(),
              textColor: AppColors.blackColor,
              backgroundColor: AppColors.whiteColor,
              svgIcon: AppAssets.allergy_info_icon,
              isLargeText: true,
              iconSize: 36.w,
            ).onPress(() {
              medicalFileViewModel.getPatientAllergiesList();
              Navigator.of(context).push(
                CustomPageRoute(
                  page: AllergiesListPage(),
                ),
              );
            }),
            MedicalFileCard(
              label: LocaleKeys.vaccineInfomation.tr(),
              textColor: AppColors.blackColor,
              backgroundColor: AppColors.whiteColor,
              svgIcon: AppAssets.vaccine_info_icon,
              isLargeText: true,
              iconSize: 36.w,
            ).onPress(() {
              Navigator.of(context).push(
                CustomPageRoute(
                  page: VaccineListPage(),
                ),
              );
            }),
          ],
        ).paddingSymmetrical(0.w, 0.0),
        SizedBox(height: 24.h),
      ],
    );
  }

  Widget buildRequestsTab() {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            (!appState.isArabic()
                    ? "${LocaleKeys.sick2.tr(context: context)} ${LocaleKeys.sickSubtitle.tr(context: context)}"
                    : "${LocaleKeys.sickSubtitle.tr(context: context)} ${LocaleKeys.sick2.tr(context: context)}")
                .toText16(isBold: true),
            Row(
              children: [
                LocaleKeys.viewAll.tr(context: context).toText12(color: AppColors.primaryRedColor, isBold: true),
                SizedBox(width: 2.h),
                Icon(Icons.arrow_forward_ios, color: AppColors.primaryRedColor, size: 10.h),
              ],
            ),
          ],
        ).onPress(() {
          Navigator.of(context).push(
            CustomPageRoute(
              page: PatientSickleavesListPage(),
            ),
          );
        }),
        SizedBox(height: 16.h),
        Consumer<MedicalFileViewModel>(builder: (context, medicalFileVM, child) {
          return medicalFileVM.isPatientSickLeaveListLoading
              ? PatientSickLeaveCard(
                  patientSickLeavesResponseModel: PatientSickLeavesResponseModel(),
                  isLoading: true,
                ).paddingSymmetrical(0.w, 0.0)
              : medicalFileVM.patientSickLeaveList.isNotEmpty
                  ? PatientSickLeaveCard(
                      patientSickLeavesResponseModel: medicalFileVM.patientSickLeaveList.first,
                      isLoading: false,
                    ).paddingSymmetrical(0.w, 0.0)
                  : Container(
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                        color: AppColors.whiteColor,
                        borderRadius: 12.r,
                        hasShadow: false,
                      ),
                      child: Utils.getNoDataWidget(
                        context,
                        noDataText: LocaleKeys.youDontHaveAnySickLeavesYet.tr(context: context),
                        isSmallWidget: true,
                        width: 62.h,
                        height: 62.h,
                      ),
                    );
        }),
        SizedBox(height: 16.h),
        Selector<MedicalFileViewModel, ({bool isLoading, List<PatientMedicalReportResponseModel> listRequest, List<PatientMedicalReportResponseModel> listReady})>(
          selector: (context, vm) => (isLoading: vm.isPatientMedicalReportsListLoading, listRequest: vm.patientMedicalReportRequestedList, listReady: vm.patientMedicalReportReadyList),
          builder: (context, data, _) {
            return MedicalReportCard(isLoading: data.isLoading, listRequest: data.listRequest, listReady: data.listReady);
          },
        ),
        SizedBox(height: 24.h),
      ],
    );
  }

  Widget buildHealthToolsTab() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        GridView(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 10.h,
            mainAxisSpacing: 16.w,
            childAspectRatio: isFoldable ? 1.2 : (isTablet ? 1.4 : 0.98),
          ),
          physics: NeverScrollableScrollPhysics(),
          padding: EdgeInsets.only(top: 12.h),
          shrinkWrap: true,
          children: [
            // Health Trackers
            HealthToolsCard(
              label: LocaleKeys.healthTrackers.tr(context: context),
              textColor: AppColors.blackColor,
              svgIcon: AppAssets.general_health,
              iconColor: null,
              iconSize: 24.w,
            ).onPress(() {
              if (getIt.get<AppState>().isAuthenticated) {
                context.navigateWithName(AppRoutes.healthTrackersPage);
              }
            }),
            // Daily Water Monitor
            HealthToolsCard(
              label: LocaleKeys.dailyWaterMonitor.tr(context: context),
              textColor: AppColors.blackColor,
              svgIcon: AppAssets.daily_water_monitor_icon,
              iconColor: AppColors.infoColor,
              iconSize: 24.w,
            ).onPress(() async {
              if (getIt.get<AppState>().isAuthenticated) {
                LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingYourWaterIntakeDetails.tr());
                final waterMonitorVM = getIt.get<WaterMonitorViewModel>();
                await waterMonitorVM.fetchUserDetailsForMonitoring(
                  onSuccess: (userDetail) {
                    LoaderBottomSheet.hideLoader();
                    if (userDetail == null) {
                      waterMonitorVM.populateFromAuthenticatedUser();
                      context.navigateWithName(AppRoutes.waterMonitorSettingsPage);
                    } else {
                      context.navigateWithName(AppRoutes.waterConsumptionPage);
                    }
                  },
                  onError: (error) {
                    LoaderBottomSheet.hideLoader();
                    context.navigateWithName(AppRoutes.waterConsumptionPage);
                  },
                );
              }
            }),
            // Health Calculators
            HealthToolsCard(
              label: LocaleKeys.healthCalculatorsServices.tr(context: context),
              textColor: AppColors.blackColor,
              svgIcon: AppAssets.health_calculators_services_icon,
              iconColor: AppColors.successColor,
              iconSize: 24.w,
            ).onPress(() {
              context.navigateWithName(AppRoutes.healthCalculatorsPage);
            }),
            // Health Converters
            HealthToolsCard(
              label: LocaleKeys.healthConvertersServices.tr(context: context),
              textColor: AppColors.blackColor,
              svgIcon: AppAssets.health_converters_icon,
              iconColor: AppColors.primaryRedColor,
              iconSize: 24.w,
            ).onPress(() {
              context.navigateWithName(AppRoutes.healthConvertersPage);
            }),
            // Smart Watches
            HealthToolsCard(
              label: LocaleKeys.smartWatchesServices.tr(context: context),
              textColor: AppColors.blackColor,
              svgIcon: AppAssets.smartwatch_icon,
              iconColor: AppColors.warningColorYellow,
              iconSize: 24.w,
            ).onPress(() {
              if (getIt.get<AppState>().isAuthenticated) {
                context.navigateWithName(AppRoutes.smartWatches);
              }
            }),
          ],
        ).paddingSymmetrical(0.w, 0.0),
        SizedBox(height: 24.h),
      ],
    );
  }

  Widget getSelectedTabData(int index) {
    switch (index) {
      case 0:
        //General Tab Data
        return buildMedicalServicesTab();
      case 1:
        //Insurance Tab Data
        return buildInsuranceTab(index);
      case 2:
        // Requests Tab Data
        return buildRequestsTab();
      case 3:
        // Health Tools Tab Data
        return buildHealthToolsTab();
      default:
        return Container();
    }
  }

  // Build shimmer for vital signs
  Widget _buildVitalSignShimmer() {
    return Row(
      children: [
        Expanded(child: _buildSingleShimmerCard()),
        SizedBox(width: 12.w),
        Expanded(child: _buildSingleShimmerCard()),
      ],
    );
  }

  Widget _buildSingleShimmerCard() {
    return Container(
      decoration: BoxDecoration(
        color: AppColors.whiteColor,
        borderRadius: BorderRadius.circular(16.r),
      ),
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 20.h),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // Icon shimmer at top
            Container(
              width: 44.w,
              height: 44.h,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12.r),
              ),
            ).toShimmer(),
            SizedBox(height: 16.h),
            // Label shimmer
            // Container(
            //   width: 70.w,
            //   height: 12.h,
            //   decoration: BoxDecoration(
            //     borderRadius: BorderRadius.circular(4.r),
            //   ),
            // ).toShimmer(),
            // SizedBox(height: 8.h),
            // Value shimmer (larger)
            // Container(
            //   width: 60.w,
            //   height: 32.h,
            //   decoration: BoxDecoration(
            //     borderRadius: BorderRadius.circular(4.r),
            //   ),
            // ).toShimmer(),
            // SizedBox(height: 12.h),
            // Bottom row with chip and arrow
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  width: 60.w,
                  height: 20.h,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                ).toShimmer(),
                Container(
                  width: 16.w,
                  height: 16.h,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(2.r),
                  ),
                ).toShimmer(),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // Build pages with 2 cards each
  List<Widget> _buildVitalSignPages({
    required VitalSignResModel vitalSign,
    required VoidCallback onTap,
    required int currentPageIndex,
  }) {
    return [
      // Page 1: BMI + Height
      Padding(
        padding: EdgeInsets.symmetric(horizontal: 24.w),
        child: Row(
          children: [
            Expanded(
              child: _buildVitalSignCard(
                icon: AppAssets.bmiVital,
                label: LocaleKeys.bmi.tr(context: context),
                value: _formatValue(vitalSign.bodyMassIndex),
                unit: '',
                status: vitalSign.bodyMassIndex != null ? _getBMIStatus(vitalSign.bodyMassIndex) : null,
                // status: "Overweight",
                onTap: onTap,
              ),
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: _buildVitalSignCard(
                icon: AppAssets.heightVital,
                label: LocaleKeys.height.tr(context: context),
                value: _formatValue(vitalSign.heightCm),
                unit: LocaleKeys.cm.tr(),
                status: null,
                onTap: onTap,
              ),
            ),
          ],
        ),
      ),
      // Page 2: Weight + Blood Pressure
      Padding(
          padding: EdgeInsets.symmetric(horizontal: 24.w),
          child: Row(
            children: [
              Expanded(
                child: _buildVitalSignCard(
                  icon: AppAssets.weightVital,
                  label: LocaleKeys.weight.tr(context: context),
                  value: _formatValue(vitalSign.weightKg),
                  unit: LocaleKeys.kg.tr(),
                  status: vitalSign.weightKg != null ? _getWeightStatus(vitalSign.bodyMassIndex) : null,
                  onTap: onTap,
                ),
              ),
              SizedBox(width: 12.w),
              Expanded(
                child: _buildVitalSignCard(
                  icon: AppAssets.bloodPressure,
                  label: LocaleKeys.bloodPressure.tr(context: context),
                  value: (vitalSign.bloodPressureLower != null && vitalSign.bloodPressureHigher != null && vitalSign.bloodPressureLower != 0 && vitalSign.bloodPressureHigher != 0)
                      ? "${vitalSign.bloodPressureHigher}/${vitalSign.bloodPressureLower}"
                      : '--',
                  unit: '',
                  status: (vitalSign.bloodPressureLower != null && vitalSign.bloodPressureHigher != null && vitalSign.bloodPressureLower != 0 && vitalSign.bloodPressureHigher != 0)
                      ? _getBloodPressureStatus(
                          systolic: vitalSign.bloodPressureHigher,
                          diastolic: vitalSign.bloodPressureLower,
                        )
                      : null,
                  onTap: onTap,
                ),
              ),
            ],
          )),
    ];
  }

  VitalSignStatus? _getBMIStatus(dynamic bmi) {
    return VitalSignUiModel.bmiStatus(bmi);
  }

  VitalSignStatus? _getWeightStatus(dynamic bmi) {
    return VitalSignUiModel.weightStatus(bmi);
  }

  VitalSignStatus? _getBloodPressureStatus({dynamic systolic, dynamic diastolic}) {
    return VitalSignUiModel.bloodPressureStatus(systolic: systolic, diastolic: diastolic);
  }

  // Helper function to format vital sign values, showing '--' instead of 0 or null
  String _formatValue(dynamic value) {
    if (value == null) return '--';
    if (value is num && value == 0) return '--';
    if (value is String) {
      if (value.trim().isEmpty) return '--';
      final parsed = double.tryParse(value);
      if (parsed == null || parsed == 0) return '--';
    }
    return value.toString();
  }

  Widget _buildVitalSignCard({
    required String icon,
    required String label,
    required String value,
    required String unit,
    required VitalSignStatus? status,
    required VoidCallback onTap,
  }) {
    final VitalSignUiModel scheme = VitalSignUiModel.scheme(status: status, label: label);

    return GestureDetector(
      onTap: onTap,
      child: Container(
        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
          color: AppColors.whiteColor,
          borderRadius: 16.r,
          hasShadow: false,
        ),
        child: Padding(
          padding: EdgeInsets.all(16.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Container(
                    padding: EdgeInsets.all(8.h),
                    decoration: BoxDecoration(
                      color: scheme.iconBg,
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Utils.buildSvgWithAssets(
                      icon: icon,
                      width: 22.h,
                      height: 22.h,
                      iconColor: scheme.iconFg,
                      fit: BoxFit.contain,
                    ),
                  ),
                  SizedBox(width: 10.w),
                  Expanded(
                    child: label.toText14(
                      color: AppColors.textColor,
                      weight: FontWeight.w600,
                    ),
                  ),
                  Utils.buildSvgWithAssets(icon: getIt.get<AppState>().isArabic() ? AppAssets.arrow_back : AppAssets.arrow_forward, width: 18.w, height: 18.h),
                ],
              ),
              Spacer(),
              // SizedBox(height: 14.h),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 6.h),
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                  color: AppColors.bgScaffoldColor,
                  borderRadius: 10.r,
                  hasShadow: false,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Flexible(
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Flexible(
                            child: value.toText17(isBold: true, color: AppColors.textColor, isEnglishOnly: true),
                          ),
                          if (unit.isNotEmpty && value != '--' && value != '0') ...[
                            SizedBox(width: 3.w),
                            unit.toText12(
                              color: AppColors.textColor,
                              isBold: true,
                            ),
                          ],
                        ],
                      ),
                    ),
                    if (status != null) ...[
                      SizedBox(width: 4.w),
                      AppCustomChipWidget(
                        labelText: VitalSignUiModel.statusToString(status),
                        backgroundColor: scheme.chipBg,
                        textColor: scheme.chipFg,
                      ),
                    ] else
                      AppCustomChipWidget(
                        labelText: "",
                        backgroundColor: AppColors.bgScaffoldColor,
                        textColor: null,
                      )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
