import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';

class UserAvatarWidget extends StatelessWidget {
  final double width;
  final double height;
  final int? gender;
  final int? age;
  final BoxFit? fit;
  final bool isCircular;
  final double? borderRadius;
  final String? customProfileImageData; // For family members or other users
  final bool isFamilyMember; // New flag to prevent AppState fallback

  const UserAvatarWidget({
    Key? key,
    required this.width,
    required this.height,
    this.gender,
    this.age,
    this.fit,
    this.isCircular = false,
    this.borderRadius,
    this.customProfileImageData,
    this.isFamilyMember = false, // Default to false for backward compatibility
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final appState = getIt.get<AppState>();
    final userGender = gender ?? appState.getAuthenticatedUser()?.gender ?? 1;
    final userAge = age ?? appState.getAuthenticatedUser()?.age ?? 0;

    // Determine which profile image data to use:
    // - For family members: ONLY use customProfileImageData (no AppState fallback)
    // - For main user: Use customProfileImageData if provided, otherwise AppState
    final String? profileImageData;
    if (isFamilyMember) {
      // Family member mode: only use their specific image data, no fallback
      profileImageData = customProfileImageData;
    } else {
      // Main user mode: use custom data or fall back to AppState
      profileImageData = customProfileImageData ?? appState.getProfileImageData;
    }

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

    // Calculate border radius - default to 12.r if not specified and not circular
    final effectiveBorderRadius = isCircular ? width / 2 : (borderRadius ?? 12.r);

    // Show uploaded profile image if available
    if (profileImageData != null && profileImageData.isNotEmpty) {
      try {
        final bytes = base64Decode(profileImageData);
        // Use a key based on data hash to help Flutter detect changes
        final imageKey = ValueKey('avatar_${profileImageData.hashCode}');

        final imageWidget = Image.memory(
          bytes,
          key: imageKey,
          width: width,
          height: height,
          fit: fit ?? BoxFit.cover,
          gaplessPlayback: true, // Smooth transition without flicker
        );

        return ClipRRect(
          borderRadius: BorderRadius.circular(effectiveBorderRadius),
          child: imageWidget,
        );
      } catch (e) {
        // If decoding fails, show default image
        return ClipRRect(
          borderRadius: BorderRadius.circular(effectiveBorderRadius),
          child: Utils.buildImgWithAssets(
            icon: defaultImage,
            width: width,
            height: height,
            fit: fit ?? BoxFit.cover,
          ),
        );
      }
    }

    // Show default image with rounded corners
    return ClipRRect(
      borderRadius: BorderRadius.circular(effectiveBorderRadius),
      child: Utils.buildImgWithAssets(
        icon: defaultImage,
        width: width,
        height: height,
        fit: fit ?? BoxFit.cover,
      ),
    );
  }
}

