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/utils/utils.dart';
import 'package:hmg_patient_app_new/core/utils/image_compression_helper.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.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/services/permission_service.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/image_picker.dart';
import 'package:provider/provider.dart';

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

  @override
  State<ProfilePictureWidget> createState() => _ProfilePictureWidgetState();
}

class _ProfilePictureWidgetState extends State<ProfilePictureWidget> {
  final AppState _appState = getIt.get<AppState>();
  final PermissionService _permissionService = getIt.get<PermissionService>();

  @override
  void initState() {
    super.initState();

    // Initialize view model
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      final profilePictureViewModel = context.read<ProfilePictureViewModel>();
      profilePictureViewModel.initialize();
      profilePictureViewModel.triggerInitialLoad();
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // Check for user switch
    final profilePictureViewModel = context.read<ProfilePictureViewModel>();
    if (profilePictureViewModel.isInitialLoadTriggered) {
      profilePictureViewModel.checkForUserSwitch();
    }
  }

  @override
  void didUpdateWidget(ProfilePictureWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    // Check for user switch
    context.read<ProfilePictureViewModel>().checkForUserSwitch();
  }

  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),
    );
  }

  Widget _buildProfileImage(ProfilePictureViewModel profilePictureViewModel, ProfileSettingsViewModel profileVm) {
    // Always get fresh user data
    final currentUser = _appState.getAuthenticatedUser();
    final currentPatientId = currentUser?.patientId;
    final gender = currentUser?.gender ?? 1;
    final age = currentUser?.age ?? 0;

    // Determine the default image based on gender and age
    final String defaultImage;
    if (gender == 1) {
      // Male
      defaultImage = age < 7 ? AppAssets.babyBoyImg : AppAssets.maleImg;
    } else {
      // Female
      defaultImage = age < 7 ? AppAssets.babyGirlImg : AppAssets.femaleImg;
    }

    // Show selected image if available (only during upload)
    if (profilePictureViewModel.selectedImage != null) {
      return ClipOval(
        child: Image.file(
          profilePictureViewModel.selectedImage!,
          width: 136.w,
          height: 136.h,
          fit: BoxFit.cover,
        ),
      );
    }

    // Update cache if needed
    profilePictureViewModel.updateCacheIfNeeded();

    // Show cached decoded image if available
    if (profilePictureViewModel.cachedImageBytes != null) {
      return ClipOval(
        child: Image.memory(
          profilePictureViewModel.cachedImageBytes!,
          key: ValueKey('profile_$currentPatientId'),
          width: 136.w,
          height: 136.h,
          fit: BoxFit.cover,
          gaplessPlayback: true, // Prevents blink during image rebuild
        ),
      );
    }

    // Show default image (no image data or user has no uploaded image)
    print('📷 Showing default avatar for user $currentPatientId');
    return Utils.buildImgWithAssets(
      icon: defaultImage,
      width: 136.w,
      height: 136.h,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Consumer2<ProfilePictureViewModel, ProfileSettingsViewModel>(
      builder: (context, profilePictureViewModel, profileVm, _) {
        // If we already have cached bytes, show the image even while "loading"
        // to prevent the shimmer→image blink on page open
        final bool showShimmer = profilePictureViewModel.shouldShowShimmer();

        return Center(
          child: Stack(
            children: [
              // Profile Image — use ValueListenableBuilder for targeted updates
              ValueListenableBuilder<int>(
                valueListenable: profilePictureViewModel.profileImageVersion,
                builder: (context, version, child) {
                  return AnimatedSwitcher(
                    duration: const Duration(milliseconds: 200),
                    child: showShimmer
                        ? Container(
                            key: const ValueKey('shimmer'),
                            width: 136.w,
                            height: 136.h,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              color: AppColors.greyTextColor.withValues(alpha: 0.2),
                            ),
                          ).toShimmer2(isShow: true)
                        : _buildProfileImage(profilePictureViewModel, profileVm),
                  );
                },
              ),

              // Edit button
              Positioned(
                right: 0,
                top: 0,
                child: GestureDetector(
                  onTap: () {
                    if (!profileVm.isUploadingProfileImage) {
                      _pickImage();
                    }
                  },
                  child: Container(
                    width: 32.w,
                    height: 32.h,
                    decoration: BoxDecoration(
                      color: AppColors.primaryRedColor,
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: AppColors.whiteColor,
                        width: 2.w,
                      ),
                    ),
                    child: profileVm.isUploadingProfileImage
                        ? SizedBox(
                            width: 16.w,
                            height: 16.h,
                            child: CircularProgressIndicator(
                              strokeWidth: 2.w,
                              valueColor: AlwaysStoppedAnimation<Color>(
                                AppColors.whiteColor,
                              ),
                            ).paddingAll(8.w),
                          )
                        : Icon(
                            Icons.camera_alt,
                            color: AppColors.whiteColor,
                            size: 16.w,
                          ),
                  ),
                ),
              ),
            ],
          ).paddingOnly(bottom: 24.h),
        );
      },
    );
  }
}
