import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_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/enums.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/core/utils/image_compression_helper.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/habib_wallet/habib_wallet_view_model.dart';
import 'package:hmg_patient_app_new/features/insurance/insurance_view_model.dart';
import 'package:hmg_patient_app_new/features/medical_file/models/family_file_response_model.dart';
import 'package:hmg_patient_app_new/features/profile_picture/profile_picture_view_model.dart';
import 'package:hmg_patient_app_new/features/profile_settings/profile_settings_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/insurance/widgets/insurance_update_details_card.dart';
import 'package:hmg_patient_app_new/services/dialog_service.dart';
import 'package:hmg_patient_app_new/services/navigation_service.dart';
import 'package:hmg_patient_app_new/services/permission_service.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package: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/chip/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/user_avatar_widget.dart';
import 'package:hmg_patient_app_new/widgets/image_picker.dart';
import 'package:provider/provider.dart';

class FamilyCards extends StatefulWidget {
  final List<FamilyFileResponseModelLists> profiles;
  late List<FamilyFileResponseModelLists>? profileViewList;
  final Function(FamilyFileResponseModelLists) onSelect;
  final Function(FamilyFileResponseModelLists) onRemove;
  final bool isShowDetails;
  final bool isBottomSheet;
  final bool isRequestDesign;
  final bool isLeftAligned;
  final bool isShowRemoveButton;
  final bool isForWalletRecharge;

  FamilyCards(
      {super.key,
      required this.profiles,
      required this.onSelect,
      required this.onRemove,
      this.profileViewList,
      this.isShowDetails = false,
      this.isBottomSheet = false,
      this.isRequestDesign = false,
      this.isLeftAligned = false,
      this.isForWalletRecharge = false,
      this.isShowRemoveButton = false});

  @override
  State<FamilyCards> createState() => _FamilyCardsState();
}

class _FamilyCardsState extends State<FamilyCards> {
  AppState appState = getIt<AppState>();
  final PermissionService _permissionService = getIt<PermissionService>();
  late InsuranceViewModel insuranceViewModel;
  late ProfileSettingsViewModel profileSettingsViewModel;

  @override
  void initState() {
    scheduleMicrotask(() {
      insuranceViewModel.initInsuranceProvider();
    });
    super.initState();
  }

  void _pickImage() {
    final profilePictureViewModel = context.read<ProfilePictureViewModel>();

    profilePictureViewModel.pickImage(
      context,
      showImagePicker: ImageOptions.showImageOptionsNew,
      compressImage: ImageCompressionHelper.compressAndResizeImage,
      onSuccess: (data) {
        if (mounted) {
          Utils.showToast(LocaleKeys.profileImageUpdatedSuccessfully.tr(context: context));
        }
      },
      onError: (error) {
        if (mounted) {
          Utils.showToast(error);
        }
      },
      imageSizeTooLargeMessage: LocaleKeys.imageSizeTooLarge.tr(context: context),
      failedToProcessImageMessage: LocaleKeys.failedToProcessImage.tr(context: context),
      checkCameraPermission: (ctx) => _permissionService.checkCameraPermission(ctx),
      checkGalleryPermission: (ctx) => _permissionService.checkGalleryPermission(ctx),
    );
  }

  double _calculateAspectRatio(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    final itemWidth = (screenWidth - 32.w - 10.w) / 2;
    double itemHeight = 0;
    itemHeight += 30.h; // 15.h top + 15.h bottom
    itemHeight += 70.h;
    itemHeight += 8.h;
    itemHeight += 20.h;

    if (widget.isShowDetails) {
      itemHeight += 4.h;
      itemHeight += 30.h;
      itemHeight += 8.h;
    } else {
      itemHeight += 4.h;
    }

    itemHeight += 70.h;
    final aspectRatio = itemWidth / itemHeight;
    return aspectRatio;
  }

  @override
  Widget build(BuildContext context) {
    widget.profileViewList = [];
    widget.profileViewList!.addAll(widget.profiles);
    widget.profileViewList!.removeWhere((element) => element.responseId == appState.getAuthenticatedUser()?.patientId);
    insuranceViewModel = Provider.of<InsuranceViewModel>(context, listen: false);
    profileSettingsViewModel = Provider.of<ProfileSettingsViewModel>(context, listen: false);
    DialogService dialogService = getIt.get<DialogService>();
    if (widget.isRequestDesign) {
      return Column(
        children: [
          // Row(
          //   children: [
          //     Utils.buildSvgWithAssets(icon: AppAssets.alertSquare),
          //     SizedBox(width: 8.h),
          //     LocaleKeys.whoCanViewMyMedicalFile.tr(context: context).toText14(color: AppColors.textColor, isUnderLine: true, isBold: true).onPress(() {
          //       dialogService.showFamilyBottomSheetWithoutHWithChild(
          //         label: LocaleKeys.manageFiles.tr(context: context),
          //         message: "",
          //         child: manageFamily(),
          //         onOkPressed: () {},
          //       );
          //     }),
          //     SizedBox(width: 4.h),
          //     Transform.flip(
          //         flipX: getIt.get<AppState>().isArabic(),
          //         child: Utils.buildSvgWithAssets(
          //           icon: AppAssets.arrowRight,
          //           iconColor: AppColors.blackColor,
          //           width: 22.w,
          //           height: 22.h,
          //           fit: BoxFit.contain,
          //         )),
          //   ],
          // ),
          // SizedBox(height: 24.h),
          CustomExpandableList(
            expansionMode: ExpansionMode.multiple,
            dividerColor: AppColors.dividerColor,
            itemPadding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 14.h),
            items: [
              ExpandableListItem(
                title: LocaleKeys.whoCanViewMyMedicalFile.tr(context: context).toText18(isBold: true),
                expandedBackgroundColor: Colors.transparent,
                initiallyExpanded: true,
                children: [
                  SizedBox(height: 10.h),
                  manageFamily()
                ],
              ),
              ExpandableListItem(title: LocaleKeys.notifications.tr(context: context).toText18(isBold: true), expandedBackgroundColor: Colors.transparent, initiallyExpanded: true, children: [
                SizedBox(height: 10.h),
                widget.profileViewList!.where((profile) => profile.isRequestFromMySide ?? false).isEmpty
                    ? Utils.getNoDataWidget(context)
                    : ListView.builder(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  padding: EdgeInsets.zero,
                  itemCount: widget.profileViewList!.where((profile) => profile.isRequestFromMySide ?? false).length,
                  itemBuilder: (context, index) {
                    final mySideProfiles = widget.profileViewList!.where((profile) => profile.isRequestFromMySide ?? false).toList();
                    FamilyFileResponseModelLists profile = mySideProfiles[index];
                    return Container(
                      margin: EdgeInsets.only(bottom: 12.h),
                      padding: EdgeInsets.symmetric(vertical: 15.h, horizontal: 15.h),
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24),
                      child: Opacity(
                        opacity: 1.0,
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            AppCustomChipWidget(
                              labelText: profile.statusDescription ?? " N/A",
                              backgroundColor: profile.status == FamilyFileEnum.pending.toInt
                                  ? AppColors.alertLightColor.withValues(alpha: 0.20)
                                  : profile.status == FamilyFileEnum.rejected.toInt
                                  ? AppColors.primaryRedColor.withValues(alpha: 0.20)
                                  : profile.status == FamilyFileEnum.active.toInt
                                  ? AppColors.lightGreenColor
                                  : AppColors.lightGrayBGColor,
                                textColor: profile.status == FamilyFileEnum.pending.toInt
                                    ? AppColors.alertLightColor
                                    : profile.status == FamilyFileEnum.rejected.toInt
                                    ? AppColors.primaryRedColor
                                    : profile.status == FamilyFileEnum.active.toInt
                                    ? AppColors.textGreenColor
                                    : AppColors.alertColor
                            ),
                            SizedBox(height: 8.h),
                            Wrap(alignment: WrapAlignment.start, crossAxisAlignment: WrapCrossAlignment.start, runAlignment: WrapAlignment.start, spacing: 0.h, children: [
                              (profile.patientName ?? "").toText14(isBold: true, isCenter: false, maxlines: 1),
                              (getStatusTextByRequest(FamilyFileEnum.values.firstWhere((e) => e.toInt == profile.status), profile.isRequestFromMySide ?? false))
                                  .toText12(isCenter: false, maxLine: 1, isBold: true, color: AppColors.greyTextColor),
                            ]),
                            SizedBox(height: 8.h),
                            AppCustomChipWidget(
                              labelText: "Medical File: ${profile.responseId ?? "N/A"}",
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                ),
              ])
            ],
            theme: ExpandableListTheme.custom(
              defaultTrailingIcon: Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, height: 22.h, width: 22.w, iconColor: AppColors.textColor),
            ),
          ).paddingSymmetrical(0.w, 0.0),
          SizedBox(height: 20.h),
        ],
      );
    } else {
      return Column(
        children: [
          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: [
                      Stack(
                        children: [
                          UserAvatarWidget(
                            width: 56.w,
                            height: 56.h,
                            fit: BoxFit.cover,
                            isCircular: true,
                          ),
                          // Camera/Edit button
                          Positioned(
                            right: 0,
                            bottom: 0,
                            child: Consumer<ProfileSettingsViewModel>(
                              builder: (context, profileVm, _) {
                                return GestureDetector(
                                  onTap: () {
                                    if (!profileVm.isUploadingProfileImage) {
                                      _pickImage();
                                    }
                                  },
                                  child: Container(
                                    width: 20.w,
                                    height: 20.h,
                                    decoration: BoxDecoration(
                                      color: AppColors.primaryRedColor,
                                      shape: BoxShape.circle,
                                      border: Border.all(
                                        color: AppColors.whiteColor,
                                        width: 1.5.w,
                                      ),
                                    ),
                                    child: profileVm.isUploadingProfileImage
                                        ? SizedBox(
                                            width: 10.w,
                                            height: 10.h,
                                            child: CircularProgressIndicator(
                                              strokeWidth: 1.5.w,
                                              valueColor: AlwaysStoppedAnimation<Color>(
                                                AppColors.whiteColor,
                                              ),
                                            ).paddingAll(4.w),
                                          )
                                        : Icon(
                                            Icons.camera_alt,
                                            color: AppColors.whiteColor,
                                            size: 10.w,
                                          ),
                                  ),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                      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,
                                richText: "${LocaleKeys.fileno.tr(context: context)}: ${appState.getAuthenticatedUser()!.patientId}".toText10(isBold: true),
                                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.withValues(alpha: 0.1)
                              : insuranceVM.isInsuranceActive
                                  ? AppColors.successColor.withValues(alpha: 0.1)
                                  : AppColors.warningColorYellow.withValues(alpha: 0.1),
                          labelPadding: EdgeInsetsDirectional.only(start: -4.w, end: insuranceVM.isInsuranceActive ? 6.w : 0.w),
                        ).toShimmer2(isShow: insuranceVM.isInsuranceLoading);
                      }),
                    ],
                  ),
                ],
              ),
            ),
          ).paddingSymmetrical(0.w, 0.0),
          SizedBox(height: 16.h),
          GridView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemCount: widget.profileViewList!.length,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 10.w,
              mainAxisSpacing: 10.h,
              childAspectRatio: _calculateAspectRatio(context),
            ),
            padding: EdgeInsets.only(bottom: 20.h),
            itemBuilder: (context, index) {
              final profile = widget.profileViewList![index];
              final isActive = (profile.responseId == appState.getAuthenticatedUser()?.patientId);
              final isParentUser = appState.getAuthenticatedUser()?.isParentUser ?? false;
              final isSuperUser = appState.getUserSwitchPayloads;
              // TODO: canSwitch functionality is currently disabled - set to true to allow all switches
              // Original logic: final canSwitch = isParentUser || (!isParentUser && profile.responseId == appState.getSuperUserID);
              final canSwitch = true; // Disabled - allows all users to switch
              return Container(
                padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 12.h),
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r),
                child: Opacity(
                  opacity: isActive || profile.status == FamilyFileEnum.pending.toInt || !canSwitch ? 0.4 : 1.0, // Fade all content if active
                  child: Stack(
                    children: [
                      Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          UserAvatarWidget(
                            width: 70.h,
                            height: 66.h,
                            gender: profile.gender,
                            age: profile.age,
                            fit: BoxFit.cover,
                            customProfileImageData: profile.patientImageData,
                            isCircular: true,
                            isFamilyMember: true, // Prevent AppState fallback
                          ),
                          SizedBox(height: 4.h),
                          (profile.patientName ?? "Unknown").toText14(isBold: true, isCenter: true, maxlines: 1),
                          // SizedBox(height: 8.h),
                          // CustomChipWidget(
                          //     chipType: ChipTypeEnum.alert,
                          //     backgroundColor: AppColors.lightGrayBGColor,
                          //     chipText: "${LocaleKeys.relationship.tr(context: context)}: ${profile.relationship ?? " N/A"}",
                          //     iconAsset: AppAssets.heart,
                          //     isShowBorder: false,
                          //     borderRadius: 8.h,
                          //     textColor: AppColors.textColor),
                          widget.isShowDetails ? SizedBox(height: 4.h) : SizedBox(),
                          widget.isShowDetails
                              ? Wrap(direction: Axis.horizontal, spacing: 4.h, runSpacing: 4.h, children: [
                                  AppCustomChipWidget(
                                    icon: AppAssets.file_icon,
                                    richText: "${LocaleKeys.fileno.tr(context: context)}: ${profile.responseId}".toText10(isBold: true),
                                    labelPadding: EdgeInsetsDirectional.only(start: -4.w, end: 6.w),
                                  ),
                                  AppCustomChipWidget(
                                    labelText: "${LocaleKeys.age.tr(context: context)}: ${profile.age ?? "N/A"} ${LocaleKeys.years.tr(context: context)}",
                                    labelPadding: EdgeInsetsDirectional.only(start: 4.w, end: 6.w),
                                  ),
                                ])
                              : SizedBox(),
                          widget.isShowDetails
                              ? SizedBox(height: 8.h)
                              : SizedBox(
                                  height: 4.h,
                                ),
                          Spacer(),
                          widget.isForWalletRecharge
                              ? CustomButton(
                                  height: 40.h,
                                  onPressed: () {
                                    widget.onSelect(profile);
                                    // if (canSwitch) widget.onSelect(profile);
                                  },
                                  text: widget.isForWalletRecharge ? LocaleKeys.selectFamilyFile.tr() : LocaleKeys.select.tr(context: context),
                                  backgroundColor: AppColors.secondaryLightRedColor,
                                  borderColor: AppColors.secondaryLightRedColor,
                                  textColor: AppColors.primaryRedColor,
                                  fontSize: 13.h,
                                  icon: AppAssets.activeCheck,
                                  iconColor: isActive || !canSwitch ? (isActive ? null : AppColors.greyTextColor) : AppColors.primaryRedColor,
                                  padding: EdgeInsets.symmetric(vertical: 0, horizontal: 0),
                                ).paddingOnly(top: 0, bottom: 0)
                              : CustomButton(
                                  height: 40.h,
                                  onPressed: () {
                                    if (canSwitch) widget.onSelect(profile);
                                  },
                                  text: isActive ? LocaleKeys.active.tr(context: context) : LocaleKeys.switchLogin.tr(context: context),
                                  backgroundColor: isActive || !canSwitch ? Colors.grey.shade200 : AppColors.secondaryLightRedColor,
                                  borderColor: isActive || !canSwitch ? Colors.grey.shade200 : AppColors.secondaryLightRedColor,
                                  textColor: isActive || !canSwitch ? AppColors.greyTextColor : AppColors.primaryRedColor,
                                  fontSize: 13.h,
                                  icon: isActive ? AppAssets.activeCheck : AppAssets.switch_user,
                                  iconColor: isActive || !canSwitch ? (isActive ? null : AppColors.greyTextColor) : AppColors.primaryRedColor,
                                  padding: EdgeInsets.symmetric(vertical: 0, horizontal: 0),
                                ).paddingOnly(top: 0, bottom: 0),
                        ],
                      ),
                      if (widget.isShowRemoveButton) ...[
                        isParentUser ? Positioned(
                          top: 0,
                          right: 0,
                          child: Utils.buildSvgWithAssets(icon: AppAssets.deleteIcon).onPress(() {
                            if (!isActive) widget.onRemove(profile);
                          }),
                        ) : SizedBox(),
                      ],
                    ],
                  ),
                ),
              );
            },
          ),
        ],
      );
    }
  }

  Widget manageFamily() {
    NavigationService navigationService = getIt<NavigationService>();

    return widget.profileViewList!.where((profile) => !(profile.isRequestFromMySide ?? false)).isEmpty
        ? Utils.getNoDataWidget(context)
        : ListView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            padding: EdgeInsetsGeometry.zero,
            itemCount: widget.profileViewList!.where((profile) => !(profile.isRequestFromMySide ?? false)).length,
            itemBuilder: (context, index) {
              final otherProfiles = widget.profileViewList!.where((profile) => !(profile.isRequestFromMySide ?? false)).toList();
              FamilyFileResponseModelLists profile = otherProfiles[index];
              return Container(
                margin: EdgeInsets.only(bottom: 12.h),
                padding: EdgeInsets.symmetric(vertical: 15.h, horizontal: 15.h),
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24),
                child: Opacity(
                  opacity: 1.0,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      AppCustomChipWidget(
                        labelText: profile.statusDescription ?? "N/A",
                        backgroundColor: profile.status == FamilyFileEnum.pending.toInt
                            ? AppColors.alertLightColor.withValues(alpha: 0.20)
                            : profile.status == FamilyFileEnum.rejected.toInt
                                ? AppColors.primaryRedColor.withValues(alpha: 0.20)
                                : profile.status == FamilyFileEnum.active.toInt
                                    ? AppColors.lightGreenColor
                                    : AppColors.lightGrayBGColor,
                        textColor: profile.status == FamilyFileEnum.pending.toInt
                            ? AppColors.alertLightColor
                            : profile.status == FamilyFileEnum.rejected.toInt
                                ? AppColors.primaryRedColor
                                : profile.status == FamilyFileEnum.active.toInt
                                    ? AppColors.textGreenColor
                                    : AppColors.alertColor,
                      ),
                      SizedBox(height: 8.h),
                      Wrap(
                        alignment: WrapAlignment.start,
                        children: [
                          (profile.patientName ?? "").toText14(isBold: true, isCenter: true, maxlines: 1),
                          SizedBox(
                            width: 2.w,
                          ),
                          (getStatusTextByRequest(FamilyFileEnum.values.firstWhere((e) => e.toInt == profile.status), profile.isRequestFromMySide ?? false)).toText14(
                            isBold: false,
                            isCenter: true,
                            maxlines: 1,
                            weight: FontWeight.w600,
                            color: AppColors.greyTextColor,
                          ),
                        ],
                      ),
                      SizedBox(height: 8.h),
                      AppCustomChipWidget(
                        labelText: "${LocaleKeys.medicalFile.tr(context: context)}: ${profile.patientId ?? "N/A"}",
                      ),
                      SizedBox(height: 16.h),
                      Row(
                        children: [
                          profile.status == FamilyFileEnum.active.toInt
                              ? SizedBox()
                              : Expanded(
                                  child: CustomButton(
                                    height: 40.h,
                                    fontSize: 14.f,
                                    text: LocaleKeys.acceptLbl.tr(),
                                    onPressed: () {
                                      navigationService.pop();
                                      widget.onSelect(profile);
                                    },
                                    backgroundColor: AppColors.lightGreenButtonColor,
                                    borderColor: AppColors.lightGreenButtonColor,
                                    textColor: AppColors.textGreenColor,
                                    borderWidth: 0,
                                    icon: null,
                                  ),
                                ),
                          profile.status == FamilyFileEnum.active.toInt ? SizedBox() : SizedBox(width: 8.h),
                          Expanded(
                            child: CustomButton(
                              height: 40.h,
                              fontSize: 14.f,
                              text: profile.status == FamilyFileEnum.active.toInt ? LocaleKeys.removeMember.tr() : LocaleKeys.rejectView.tr(),
                              onPressed: () {
                                navigationService.pop();
                                widget.onRemove(profile);
                              },
                              backgroundColor: AppColors.secondaryLightRedColor,
                              borderColor: AppColors.secondaryLightRedColor,
                              textColor: AppColors.primaryRedColor,
                              icon: null,
                              iconColor: AppColors.primaryRedColor,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              );
            },
          );
  }

  String getStatusTextByRequest(FamilyFileEnum status, bool isRequestFromMySide) {
    switch (status) {
      case FamilyFileEnum.active:
        if (isRequestFromMySide) {
          return LocaleKeys.acceptedYourRequestToBeYourFamilyMember.tr(namedArgs: {'status': status.displayName}, context: context);
        } else {
          return LocaleKeys.canViewYourFile.tr(context: context);
        }
      case FamilyFileEnum.pending:
        if (isRequestFromMySide) {
          return LocaleKeys.hasARequestPendingToBeYourFamilyMember.tr(namedArgs: {'status': status.displayName}, context: context);
        } else {
          return LocaleKeys.wantsToAddYouAsTheirFamilyMember.tr(context: context);
        }
      case FamilyFileEnum.rejected:
        if (isRequestFromMySide) {
          return LocaleKeys.rejectedYourRequestToBeYourFamilyMember.tr(namedArgs: {'status': status.displayName}, context: context);
        } else {
          return LocaleKeys.rejectedYourFamilyMemberRequest.tr(namedArgs: {'status': status.displayName}, context: context);
        }
      case FamilyFileEnum.inactive:
        return LocaleKeys.inactive.tr(context: context);
      default:
        return LocaleKeys.notAvailable.tr(context: context);
    }
  }
}
