import 'dart:async';
import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:hmg_patient_app_new/core/api_consts.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_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/utils.dart';
import 'package:hmg_patient_app_new/extensions/int_extensions.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.dart';
import 'package:hmg_patient_app_new/features/contact_us/contact_us_view_model.dart';
import 'package:hmg_patient_app_new/features/contact_us/models/feedback_type.dart';
import 'package:hmg_patient_app_new/features/insurance/insurance_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/family_file_response_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/contact_us/feedback_page.dart';
import 'package:hmg_patient_app_new/presentation/insurance/widgets/insurance_update_details_card.dart';
import 'package:hmg_patient_app_new/presentation/profile_settings/accessibility_page.dart';
import 'package:hmg_patient_app_new/presentation/profile_settings/widgets/profile_picture_widget.dart';
import 'package:hmg_patient_app_new/presentation/profile_settings/widgets/update_email_widget.dart';
import 'package:hmg_patient_app_new/presentation/profile_settings/widgets/update_emergency_contact_widget.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/app_language_change.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/user_avatar_widget.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:in_app_review/in_app_review.dart';

import 'dart:ui' as ui;

import 'widgets/patient_qr_code_widget.dart';

class ProfileSettings extends StatefulWidget {
  const ProfileSettings({super.key});

  @override
  ProfileSettingsState createState() => ProfileSettingsState();
}

class ProfileSettingsState extends State<ProfileSettings> {

  final InAppReview inAppReview = InAppReview.instance;

  @override
  void initState() {
    super.initState();
    _loadPermissions();
    
    // Load data after first frame
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        insuranceViewModel.initInsuranceProvider();
        // Load profile settings for preferred language
        profileSettingsViewModel.getProfileSettings();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  double dynamicItemHeight(BuildContext context) {
    final double w = SizeUtils.width;
    final double h = SizeUtils.height;

    double longer = w > h ? w : h;
    double shorter = w < h ? w : h;

    final double aspect = longer / (shorter == 0 ? 1 : shorter);

    // Choose multiplier based on aspect ratio (handles near-square / foldable)
    double multiplier;
    if (aspect < 1.05) {
      multiplier = 0.28; // nearly square / foldable -> smaller card height
    } else if (aspect > 1.8) {
      multiplier = 0.40; // very tall/wide -> larger height
    } else {
      multiplier = 0.34; // normal phones/tablets
    }

    // Compute and clamp using sensible bounds (uses .h extension)
    final double minH = 215.h;
    final double maxH = 380.h;
    final double computed = (shorter * multiplier);

    return computed.clamp(minH, maxH);
  }

  int length = 3;
  final SwiperController _controller = SwiperController();
  late InsuranceViewModel insuranceViewModel;
  late ContactUsViewModel contactUsViewModel;
  late ProfileSettingsViewModel profileSettingsViewModel;
  String _permissionsLabel = "";

  @override
  Widget build(BuildContext context) {
    insuranceViewModel = Provider.of<InsuranceViewModel>(context, listen: false);
    contactUsViewModel = Provider.of<ContactUsViewModel>(context, listen: false);
    profileSettingsViewModel = Provider.of<ProfileSettingsViewModel>(context, listen: false);
    return CollapsingListView(
      title: LocaleKeys.profileAndSettings.tr(context: context),
      logout: () {
        context.read<AuthenticationViewModel>().logout();
      },
      isClose: true,
      child: SingleChildScrollView(
        padding: EdgeInsets.only(top: 0.h, bottom: 24.h),
        physics: NeverScrollableScrollPhysics(),
        child: Consumer2<ProfileSettingsViewModel, MedicalFileViewModel>(
          builder: (context, profileVm, medicalVm, child) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Profile Picture Section
                ProfilePictureWidget(),

                // SizedBox(
                //   height: dynamicItemHeight(context) + 20 + 30, // itemHeight + shadow padding (10 top + 10 bottom) + pagination dots space
                //   child: Swiper(
                //     itemCount: medicalVm.patientFamilyFiles.length,
                //     layout: SwiperLayout.STACK,
                //     loop: true,
                //     itemHeight: dynamicItemHeight(context) + 20,
                //     // extra space for shadow
                //     itemWidth: SizeUtils.width - 30.w,
                //     indicatorLayout: PageIndicatorLayout.COLOR,
                //     axisDirection: getIt.get<AppState>().isArabic() ? AxisDirection.left : AxisDirection.right,
                //     controller: _controller,
                //     pagination: SwiperPagination(
                //       alignment: Alignment.bottomCenter,
                //       margin: EdgeInsets.only(top: (180.h + 20 + 8.h + 24.h)),
                //       builder: DotSwiperPaginationBuilder(color: Color(0xffD9D9D9), activeColor: AppColors.blackBgColor),
                //     ),
                //     itemBuilder: (BuildContext context, int index) {
                //       return Padding(
                //         padding: const EdgeInsets.symmetric(vertical: 10),
                //         child: FamilyCardWidget(
                //           profile: medicalVm.patientFamilyFiles[index],
                //           onAddFamilyMemberPress: () {
                //             DialogService dialogService = getIt.get<DialogService>();
                //             dialogService.showAddFamilyFileSheet(
                //                 label: LocaleKeys.addFamilyMember.tr(context: context),
                //                 message: LocaleKeys.pleaseFillBelowFieldToAddNewFamilyMember.tr(context: context),
                //                 onVerificationPress: () {
                //                   medicalVm.addFamilyFile(otpTypeEnum: OTPTypeEnum.sms);
                //                 });
                //           },
                //           onFamilySwitchPress: (FamilyFileResponseModelLists profile) {
                //             medicalVm.switchFamilyFiles(responseID: profile.responseId, patientID: profile.patientId, phoneNumber: profile.mobileNumber);
                //           },
                //         ).paddingOnly(right: 16.w, left: 8.w),
                //       );
                //     },
                //   ),
                // ),
                // SizedBox(height: 16.h),
                // GridView(
                //   gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: isTablet ? 3 : 2),
                //   physics: const NeverScrollableScrollPhysics(),
                //   padding: EdgeInsets.only(left: 24.w, right: 24.w, bottom: 24.h),
                //   shrinkWrap: true,
                //   children: [
                //     Container(
                //       padding: EdgeInsets.all(16.w),
                //       decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                //         color: AppColors.whiteColor,
                //         borderRadius: 20.r,
                //         hasShadow: true,
                //       ),
                //       child: Column(
                //         crossAxisAlignment: CrossAxisAlignment.start,
                //         // spacing: 4.h,
                //         children: [
                //           Row(
                //             spacing: 8.w,
                //             crossAxisAlignment: CrossAxisAlignment.center,
                //             children: [
                //               Utils.buildSvgWithAssets(icon: AppAssets.wallet, width: 40.w, height: 40.h, applyThemeColor: false),
                //               LocaleKeys.habibWallet.tr(context: context).toText16(isBold: true, maxlines: 2).expanded,
                //               Utils.buildSvgWithAssets(icon: getIt.get<AppState>().isArabic() ? AppAssets.arrow_back : AppAssets.arrow_forward),
                //             ],
                //           ),
                //           Spacer(),
                //           Consumer<HabibWalletViewModel>(builder: (context, habibWalletVM, child) {
                //             return Utils.getPaymentAmountWithSymbol2(habibWalletVM.habibWalletAmount, isExpanded: false)
                //                 .toShimmer2(isShow: habibWalletVM.isWalletAmountLoading, radius: 12.r, width: 80.w, height: 24.h);
                //           }),
                //           Spacer(),
                //           CustomButton(
                //             height: 40.h,
                //             icon: AppAssets.recharge_icon,
                //             iconSize: 22.w,
                //             iconColor: AppColors.infoColor,
                //             textColor: AppColors.infoColor,
                //             text: LocaleKeys.recharge.tr(context: context),
                //             borderWidth: 0.w,
                //             isBold: true,
                //             borderColor: Colors.transparent,
                //             backgroundColor: Color(0xff45A2F8).withValues(alpha: 0.08),
                //             padding: EdgeInsets.all(8.w),
                //             fontSize: 14.f,
                //             onPressed: () {
                //               Navigator.of(context).push(CustomPageRoute(page: RechargeWalletPage()));
                //             },
                //           ),
                //         ],
                //       ).onPress(() {
                //         Navigator.of(context).push(CustomPageRoute(page: HabibWalletPage()));
                //       }),
                //     ),
                //   ],
                // ),
                LocaleKeys.quickActions.tr(context: context).toText18(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1).paddingOnly(left: 24.w, right: 24.w),
                Container(
                  margin: EdgeInsets.only(left: 24.w, right: 24.w, top: 16.h, bottom: 24.h),
                  padding: EdgeInsets.only(top: 4.h, bottom: 4.h),
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: false),
                  child: Column(
                    children: [
                      actionItem(AppAssets.patientQRCodeIcon, LocaleKeys.viewPatientQR.tr(context: context), () {
                        showCommonBottomSheetWithoutHeight(
                          title: LocaleKeys.patientQR.tr(context: context),
                          context,
                          child: PatientQrCodeWidget(),
                          callBackFunc: () {},
                          isFullScreen: false,
                          isCloseButtonVisible: true,
                        );
                      }),
                      1.divider,
                      actionItem(AppAssets.language_change, LocaleKeys.language.tr(context: context), () {
                        showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.language.tr(context: context), child: AppLanguageChange(), callBackFunc: () {}, isFullScreen: false);
                      }, trailingLabel: Utils.appState.isArabic() ? "العربية" : "English"),
                      1.divider,
                      actionItem(AppAssets.bell, LocaleKeys.notificationsSettings.tr(context: context), () {
                        openAppSettings();
                      }),
                      1.divider,
                      Consumer<ProfileSettingsViewModel>(
                        builder: (context, profileVm, _) {
                          return actionItem(
                            AppAssets.darkModeIcon,
                            LocaleKeys.darkMode.tr(context: context),
                            () {
                              profileVm.toggleDarkMode(!profileVm.isDarkMode);
                            },
                            switchValue: profileVm.isDarkMode,
                            onSwitchChanged: (value) {
                              profileVm.toggleDarkMode(value);
                            },
                          );
                        },
                      ),
                      1.divider,
                      actionItem(AppAssets.accessibility, LocaleKeys.accessibility.tr(context: context), () {
                        Navigator.of(context).push(CustomPageRoute(page: const AccessibilityPage()));
                      }),
                    ],
                  ),
                ),
                LocaleKeys.personalInformation.tr(context: context).toText18(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1).paddingOnly(left: 24.w, right: 24.w),
                Container(
                  margin: EdgeInsets.only(left: 24.w, right: 24.w, top: 16.h, bottom: 24.h),
                  padding: EdgeInsets.only(top: 4.h, bottom: 4.h),
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: false),
                  child: Column(
                    children: [
                      actionItem(AppAssets.email_transparent, LocaleKeys.updateEmailAddress.tr(context: context), () {
                        showCommonBottomSheetWithoutHeight(
                          context,
                          title: LocaleKeys.updateEmailAddress.tr(context: context),
                          child: UpdateEmailDialog(),
                          callBackFunc: () {},
                          isFullScreen: false,
                        );
                      }),
                      1.divider,
                      actionItem(AppAssets.language, LocaleKeys.communicationLanguage.tr(context: context), () {
                        profileVm.openPreferredLanguageBottomSheet();
                      },
                          trailingLabel: profileVm.isPatientProfileLoading || profileVm.getPatientInfoForUpdate == null
                              ? "English"
                              : (profileVm.getPatientInfoForUpdate!.preferredLanguage! == "1" ? LocaleKeys.arabic.tr(context: context) : LocaleKeys.english.tr(context: context)),
                          isShowLoading: profileVm.isPatientProfileLoading),
                      1.divider,
                      actionItem(AppAssets.smart_phone_fill, LocaleKeys.emrgNo.tr(context: context), () {
                        showCommonBottomSheetWithoutHeight(
                          context,
                          title: LocaleKeys.emrgNo.tr(context: context),
                          child: UpdateEmergencyContactDialog(),
                          callBackFunc: () {},
                          isFullScreen: false,
                        );
                      }),
                      // 1.divider,
                      // actionItem(AppAssets.my_address, "My Addresses".needTranslation, () {}),
                      // 1.divider,
                      // actionItem(AppAssets.emergency, "Emergency Contact".needTranslation, () {}),
                    ],
                  ),
                ),
                LocaleKeys.helpAndSupport.tr(context: context).toText18(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1).paddingOnly(left: 24.w, right: 24.w),
                Container(
                  margin: EdgeInsets.only(left: 24.w, right: 24.w, top: 16.h),
                  padding: EdgeInsets.only(top: 4.h, bottom: 4.h),
                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: false),
                  child: Column(
                    children: [
                      actionItem(AppAssets.call_fill, LocaleKeys.contactUs.tr(context: context), () {
                        launchUrl(Uri.parse("tel://" + "+966 92 006 6666"));
                      }, trailingLabel: "92 006 6666", isEnglishOnly: true),
                      1.divider,
                      actionItem(AppAssets.permission, LocaleKeys.permissionsProfile.tr(context: context), () {
                        openAppSettings();
                      }, trailingLabel: getCurrentPermissions(), isEnglishOnly: true),
                      actionItem(AppAssets.feedbackFill, LocaleKeys.feedback.tr(context: context), () {
                        contactUsViewModel.setSelectedFeedbackType(
                          FeedbackType(id: 5, nameEN: "Not classified", nameAR: 'غير محدد'),
                        );
                        contactUsViewModel.setIsSendFeedbackTabSelected(true);
                        Navigator.pop(context);
                        Navigator.of(context).push(
                          CustomPageRoute(
                            page: FeedbackPage(),
                          ),
                        );
                      }, trailingLabel: ""),
                      1.divider,
                      // actionItem(AppAssets.permission, LocaleKeys.permissions.tr(context: context), () {}, trailingLabel: "Location, Camera"),
                      // 1.divider,
                      actionItem(AppAssets.rate, LocaleKeys.rateApp.tr(context: context), () async {
                        // if (await inAppReview.isAvailable()) {
                        //   inAppReview.requestReview();
                        // } else {
                        //   inAppReview.openStoreListing(appStoreId: '6758851027');
                        // }
                        if (Platform.isAndroid) {
                          inAppReview.openStoreListing(appStoreId: '6758851027');
                          // Utils.openWebView(
                          //   url: 'https://play.google.com/store/apps/details?id=com.ejada.hmg',
                          // );
                        } else {
                          if (await inAppReview.isAvailable()) {
                            inAppReview.requestReview();
                          }
                        }
                        // }, isExternalLink: true),
                      }),
                      1.divider,
                      actionItem(AppAssets.privacy_terms, LocaleKeys.privacyPolicy.tr(context: context), () {
                        Utils.openWebView(
                          url: AppUrls.hmgPrivacyUrlEn,
                        );
                      }, isExternalLink: true),
                      1.divider,
                      actionItem(AppAssets.privacy_terms, LocaleKeys.termsConditoins.tr(context: context), () {
                        Utils.openWebView(
                          url: AppUrls.hmgTermsUrlEn,
                        );
                      }, isExternalLink: true),
                      1.divider,
                      socialMedia(AppAssets.privacy_terms, LocaleKeys.followUsOn.tr(context: context)),
                    ],
                  ),
                ),
                // CustomButton(
                //   height: 56.h,
                //   icon: AppAssets.minus,
                //   text: LocaleKeys.deactivateAccount.tr(context: context),
                //   onPressed: () {},
                // ).paddingAll(24.w),
              ],
            );
          },
        ),
      ),
    );
  }

  Future<void> _loadPermissions() async {
    final Map<String, Permission> permissionMap = {
      'Camera': Permission.camera,
      'Microphone': Permission.microphone,
      'Location': Permission.location,
      'Notifications': Permission.notification,
      'Calendar': Permission.calendarFullAccess,
    };

    final List<String> granted = [];

    for (final entry in permissionMap.entries) {
      if (await entry.value.isGranted) {
        granted.add(entry.key);
      }
    }

    if (mounted) {
      setState(() {
        _permissionsLabel = granted.isEmpty ? 'No permissions granted' : granted.join(', ');
      });
    }
  }

  String getCurrentPermissions() {
    return _permissionsLabel;
  }

  Widget actionItem(String icon, String label, VoidCallback onPress,
      {String trailingLabel = "", bool? switchValue, ValueChanged<bool>? onSwitchChanged, bool isExternalLink = false, bool isShowLoading = false, bool isEnglishOnly = false}) {
    return SizedBox(
      height: 56.h,
      child: Row(
        spacing: 8.w,
        children: [
          Utils.buildSvgWithAssets(icon: icon, iconColor: AppColors.greyTextColor),
          label.toText14(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1).expanded,
          if (trailingLabel.isNotEmpty)
            ConstrainedBox(
              constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.35),
              child: isEnglishOnly ? Directionality(textDirection: ui.TextDirection.ltr, child: trailingLabel.toText14(color: AppColors.greyTextColor, isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1, isEnglishOnly: isEnglishOnly).toShimmer2(isShow: isShowLoading)) : trailingLabel.toText14(color: AppColors.greyTextColor, isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1, isEnglishOnly: isEnglishOnly).toShimmer2(isShow: isShowLoading),
            ),
          switchValue != null
              ? Switch(
                  value: switchValue,
                  onChanged: onSwitchChanged ?? (value) {},
                  activeThumbColor: AppColors.successColor,
                  activeTrackColor: AppColors.successColor.withValues(alpha: .15),
                )
              : Transform.scale(
                  scaleX: Utils.appState.isArabic() ? -1 : 1,
                  child: Utils.buildSvgWithAssets(icon: isExternalLink ? AppAssets.externalLink : AppAssets.arrow_forward),
                )
        ],
      ).paddingOnly(left: 16.w, right: 16.w).onPress(onPress),
    );
  }

  Widget socialMedia(String icon, String label,
      ) {
    return SizedBox(
      height: 56.h,
      child: Row(
        spacing: 8.w,
        children: [
          Utils.buildSvgWithAssets(icon: icon, iconColor: AppColors.greyTextColor),
          label.toText14(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1).expanded,

          Row(
            spacing: 24.w,
            children: [
              Utils.buildSvgWithAssets(icon: AppAssets.x2).onPress(()=> launchUrl(Uri.parse("https://twitter.com/HMG"))),
              Utils.buildSvgWithAssets(icon: AppAssets.fb).onPress(()=> launchUrl(Uri.parse("https://www.facebook.com/DrSulaimanAlHabib?ref=tn_tnmn"))),
              Utils.buildSvgWithAssets(icon: AppAssets.linkedin).onPress(()=> launchUrl(Uri.parse("https://www.linkedin.com/company/drsulaiman-alhabib-medical-group"))),
              Utils.buildSvgWithAssets(icon: AppAssets.youtube).onPress(()=> launchUrl(Uri.parse("https://www.youtube.com/c/DrsulaimanAlhabibHospitals"))),
            ],
          )
        ],
      ).paddingOnly(left: 16.w, right: 16.w),
    );
  }
}

class FamilyCardWidget extends StatefulWidget {
  final Function() onAddFamilyMemberPress;
  final Function(FamilyFileResponseModelLists member) onFamilySwitchPress;
  final FamilyFileResponseModelLists profile;

  const FamilyCardWidget({
    super.key,
    required this.onAddFamilyMemberPress,
    required this.profile,
    required this.onFamilySwitchPress(FamilyFileResponseModelLists member),
  });

  @override
  State<FamilyCardWidget> createState() => _FamilyCardWidgetState();
}

class _FamilyCardWidgetState extends State<FamilyCardWidget> {
  @override
  void initState() {
    super.initState();
    // Sync ProfileSettingsViewModel with AppState when widget is created
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        _syncProfileImageFromAppState();
      }
    });
  }

  // @override
  // void didChangeDependencies() {
  //   super.didChangeDependencies();
  //   // Also sync when dependencies change (e.g., after user switch)
  //   WidgetsBinding.instance.addPostFrameCallback((_) {
  //     if (mounted) {
  //       _syncProfileImageFromAppState();
  //     }
  //   });
  // }

  void _syncProfileImageFromAppState() {
    try {
      final profileVm = context.read<ProfileSettingsViewModel>();
      final appState = getIt.get<AppState>();

      final appStateImageData = appState.getProfileImageData;

      // Sync profile image from AppState if it's different
      if (appStateImageData != null && appStateImageData.isNotEmpty) {
        if (profileVm.profileImageData != appStateImageData) {
          print("🔄 Syncing profile image from AppState to ProfileSettingsViewModel");
          profileVm.syncProfileImageFromAppState();
        }
      } else if (profileVm.profileImageData != null) {
        // AppState is null but ViewModel has data - clear it
        print("🧹 Clearing ProfileSettingsViewModel image data (AppState is null)");
        profileVm.clearProfileImageCache();
      }
    } catch (e) {
      print("⚠️ Error syncing profile image: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    AppState appState = getIt.get<AppState>();
    final isActive = (widget.profile.responseId == appState.getAuthenticatedUser()?.patientId);
    // final isParentUser = appState.getAuthenticatedUser()?.isParentUser ?? false;
    // final canSwitch = isParentUser || (!isParentUser && widget.profile.responseId == appState.getSuperUserID);
    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.r, hasShadow: true, hasDenseShadow: true),
      child: Column(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            spacing: 8.h,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Wrap in Consumer to rebuild when ProfileSettingsViewModel changes
                  Consumer<ProfileSettingsViewModel>(
                    builder: (context, profileVm, _) {
                      final currentUserId = appState.getAuthenticatedUser()?.patientId;
                      final isCurrentUser = widget.profile.responseId == currentUserId;

                      if (isCurrentUser) {
                        // Current user - use AppState directly (like home screen profile icon)
                        return UserAvatarWidget(
                          width: 56.w,
                          height: 56.h,
                          gender: widget.profile.gender,
                          age: widget.profile.age,
                          fit: BoxFit.cover,
                          // Don't pass customProfileImageData - let it use AppState
                          isCircular: true,
                          // Don't pass isFamilyMember - allow AppState fallback
                        );
                      } else {
                        // Family member - use their specific image data
                        return UserAvatarWidget(
                          width: 56.w,
                          height: 56.h,
                          gender: widget.profile.gender,
                          age: widget.profile.age,
                          fit: BoxFit.cover,
                          customProfileImageData: widget.profile.patientImageData,
                          isCircular: true,
                          isFamilyMember: true, // Prevent AppState fallback
                        );
                      }
                    },
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      "${widget.profile.patientName}".toText18(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1, isEnglishOnly: true),
                      Wrap(
                        direction: Axis.horizontal,
                        spacing: 4.w,
                        runSpacing: 6.w,
                        children: [
                          AppCustomChipWidget(
                            labelPadding: EdgeInsetsDirectional.only(start: -6.w, end: 6.w),
                            icon: AppAssets.file_icon,
                            labelText: "${LocaleKeys.fileno.tr(context: context)}: ${widget.profile.responseId}",
                            iconSize: 12.w,
                          ),
                          isActive ? AppCustomChipWidget(
                            icon: AppAssets.checkmark_icon,
                            labelText: LocaleKeys.verified.tr(context: context),
                            iconColor: AppColors.successColor,
                            labelPadding: EdgeInsetsDirectional.only(start: -6.w, end: 6.w),
                          ) : SizedBox.shrink(),
                        ],
                      ),
                    ],
                  ).expanded,
                  // Icon(Icons.qr_code, size: 56.h)
                  Utils.buildImgWithNetwork(
                    url: "https://api.qrserver.com/v1/create-qr-code/?size=250x250&data=${widget.profile.responseId.toString()}",
                    iconColor: AppColors.transparent,
                    fit: BoxFit.contain,
                    height: 56.h,
                    width: 56.w,
                  )
                ],
              ),
              SizedBox(height: 4.h),
              SizedBox(
                child: Wrap(
                  alignment: WrapAlignment.start,
                  spacing: 4.w,
                  runSpacing: 4.h,
                  children: [
                    AppCustomChipWidget(
                      labelText: LocaleKeys.ageYearsOld.tr(namedArgs: {'age': widget.profile.age.toString(), 'yearsOld': LocaleKeys.yearsOld.tr(context: context)}),
                    ),
                    // isActive && appState.getAuthenticatedUser()!.bloodGroup != null
                    //     ?
                    isActive ? AppCustomChipWidget(
                        icon: AppAssets.blood_icon,
                            labelPadding: EdgeInsetsDirectional.only(start: -6.w, end: 8.w),
                        labelText: appState.getAuthenticatedUser()!.bloodGroup ?? "N/A",
                        iconColor: AppColors.primaryRedColor)
                    : SizedBox(),
                    Consumer<InsuranceViewModel>(builder: (context, insuranceVM, child) {
                      return isActive
                          ? 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: context),
                            //   context,
                            //   child: Utils.getWarningWidget(
                            //       loadingText: LocaleKeys.insuranceInActiveContactSupport.tr(context: context),
                            //       confirmText: LocaleKeys.contactUs.tr(context: context),
                            //       isShowActionButtons: true,
                            //       onCancelTap: () {
                            //         Navigator.pop(context);
                            //       },
                            //       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)
                          : SizedBox.shrink();
                    }),
                  ],
                ),
              ),
            ],
          ).paddingOnly(top: 16.h, right: 16.w, left: 16.w, bottom: 8.h),
          1.divider.paddingSymmetrical(16.w, 0.h),
          _buildActionButton(appState),
        ],
      ),
    );
  }

  Widget _buildActionButton(AppState appState) {
    final isParentUser = appState.getAuthenticatedUser()?.isParentUser ?? false;
    final int? currentUserId = appState.getAuthenticatedUser()?.patientId;
    final int? superUserId = appState.getSuperUserID;

    if (isParentUser) {
      return _buildParentUserButton(currentUserId);
    } else {
      return _buildNonParentUserButton(superUserId);
    }
  }

  Widget _buildParentUserButton(int? currentUserId) {
    final canSwitch = widget.profile.responseId != currentUserId;

    return CustomButton(
      icon: canSwitch ? AppAssets.switch_user : AppAssets.add_family,
      text: canSwitch ? LocaleKeys.switchAccount.tr() : LocaleKeys.addANewFamilyMember.tr(),
      onPressed: canSwitch ? () => widget.onFamilySwitchPress(widget.profile) : widget.onAddFamilyMemberPress,
      backgroundColor: canSwitch ? AppColors.secondaryLightRedColor : AppColors.primaryRedColor,
      borderColor: canSwitch ? AppColors.secondaryLightRedColor : AppColors.primaryRedColor,
      textColor: canSwitch ? AppColors.primaryRedColor : Colors.white,
      iconColor: canSwitch ? AppColors.primaryRedColor : Colors.white,
      height: isFoldable ? 50.h : 45.h,
      fontSize: 14.f,
    ).paddingOnly(top: 12.h, right: 16.w, left: 16.w, bottom: 16.h);
  }

  Widget _buildNonParentUserButton(int? superUserId) {
    final canSwitchBack = superUserId != null && superUserId == widget.profile.responseId;

    return CustomButton(
      icon: AppAssets.switch_user,
      text: canSwitchBack ? LocaleKeys.switchBackFamilyFile.tr() : LocaleKeys.switchAccount.tr(),
      backgroundColor: canSwitchBack ? AppColors.primaryRedColor : Colors.grey.shade200,
      borderColor: canSwitchBack ? AppColors.primaryRedColor : Colors.grey.shade200,
      textColor: canSwitchBack ? AppColors.whiteColor : AppColors.greyTextColor,
      iconColor: canSwitchBack ? AppColors.whiteColor : AppColors.greyTextColor,
      onPressed: canSwitchBack ? () => widget.onFamilySwitchPress(widget.profile) : () {},
      height: isFoldable ? 50.h : 40.h,
      fontSize: 14.f,
    ).paddingOnly(top: 12.h, right: 16.w, left: 16.w, bottom: 16.h);
  }

//    //TODO: Add family file switch logic here
//           isRootUser
//               ? CustomButton(icon: AppAssets.add_family, text: "Add a new family member".needTranslation, height: 40.h, fontSize: 14, onPressed: () {})
//                   .paddingOnly(top: 12, right: 16, left: 16, bottom: 16)
//               : CustomButton(
//                       icon: AppAssets.add_family,
//                       backgroundColor: AppColors.secondaryLightRedColor,
//                       borderColor: AppColors.secondaryLightRedColor,
//                       textColor: AppColors.primaryRedColor,
//                       iconColor: AppColors.primaryRedColor,
//                       text: "Switch to this medical file".needTranslation,
//                       height: 40.h,
//                       fontSize: 14,
//                       onPressed: () {})
//                   .paddingOnly(top: 12, right: 16, left: 16, bottom: 16),
//
}
