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/date_util.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/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/generated/locale_keys.g.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/user_avatar_widget.dart';
import 'package:provider/provider.dart';

class FamilyCardWidget extends StatelessWidget {
  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
  Widget build(BuildContext context) {
    AppState appState = getIt.get<AppState>();
    final isActive = (profile.responseId == appState.getAuthenticatedUser()?.patientId);
    final isParentUser = appState.getAuthenticatedUser()?.isParentUser ?? false;
    final canSwitch = isParentUser || (!isParentUser && profile.responseId == appState.getSuperUserID);
    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.r,
        hasShadow: true,
      ),
      child: Column(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            spacing: 8.h,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  UserAvatarWidget(
                    width: 56.w,
                    height: 56.h,
                    gender: profile.gender,
                    age: profile.age,
                    fit: BoxFit.cover,
                    customProfileImageData: profile.patientImageData,
                    isCircular: true,
                    isFamilyMember: true, // Prevent AppState fallback
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      "${profile.patientName}".toText18(isBold: true, textOverflow: TextOverflow.ellipsis, maxlines: 1),
                      AppCustomChipWidget(
                        icon: AppAssets.file_icon,
                        labelText: "${LocaleKeys.fileNo.tr(context: context)}: ${profile.responseId}",
                        iconSize: 12.w,
                      ),
                    ],
                  ).expanded,
                  Icon(Icons.qr_code, size: 56.h)
                ],
              ),
              SizedBox(height: 4.h),
              SizedBox(
                child: Wrap(
                  alignment: WrapAlignment.start,
                  spacing: 4.w,
                  runSpacing: 4.h,
                  children: [
                    AppCustomChipWidget(
                      labelText: "${profile.age} ${LocaleKeys.yearsOld.tr(context: context)}",
                    ),
                    isActive && appState.getAuthenticatedUser()!.bloodGroup != null
                        ? AppCustomChipWidget(
                            icon: AppAssets.blood_icon,
                            labelPadding: EdgeInsetsDirectional.only(start: -6.w, end: 8.w),
                            labelText: "Blood: ${appState.getAuthenticatedUser()!.bloodGroup ?? ""}",
                            iconColor: AppColors.primaryRedColor)
                        : SizedBox(),
                    Selector<InsuranceViewModel, ({bool isEmpty, int? patientID, bool isLoading, String? cardValidTo})>(
                      selector: (context, insuranceVM) => (
                        isEmpty: insuranceVM.patientInsuranceList.isEmpty,
                        patientID: insuranceVM.patientInsuranceList.isNotEmpty ? insuranceVM.patientInsuranceList.first.patientID : null,
                        isLoading: insuranceVM.isInsuranceLoading,
                        cardValidTo: insuranceVM.patientInsuranceList.isNotEmpty ? insuranceVM.patientInsuranceList.first.cardValidTo : null
                      ),
                      builder: (context, data, child) {
                        if (data.isEmpty) {
                          return const SizedBox();
                        } else if (profile.responseId != data.patientID) {
                          return SizedBox();
                        }

                        final isLoading = data.isLoading;
                        final isExpired = !isLoading && DateTime.now().isAfter(DateUtil.convertStringToDate(data.cardValidTo));

                        final String icon;
                        final String labelText;
                        final Color iconColor;
                        final Color backgroundColor;

                        if (isLoading) {
                          icon = AppAssets.cancel_circle_icon;
                          labelText = LocaleKeys.insurance.tr(context: context);
                          iconColor = AppColors.primaryRedColor;
                          backgroundColor = AppColors.primaryRedColor;
                        } else if (isExpired) {
                          icon = AppAssets.cancel_circle_icon;
                          labelText = LocaleKeys.insuranceExpired.tr(context: context);
                          iconColor = AppColors.primaryRedColor;
                          backgroundColor = AppColors.primaryRedColor.withValues(alpha: 0.15);
                        } else {
                          icon = AppAssets.insurance_active_icon;
                          labelText = LocaleKeys.insuranceActive.tr(context: context);
                          iconColor = AppColors.successColor;
                          backgroundColor = AppColors.successColor.withValues(alpha: 0.15);
                        }

                        return AppCustomChipWidget(
                          icon: icon,
                          labelText: labelText,
                          iconColor: iconColor,
                          iconSize: 12.w,
                          backgroundColor: backgroundColor,
                          labelPadding: EdgeInsetsDirectional.only(start: -6.w, end: 8.w),
                          // padding: EdgeInsets.zero,
                        ).toShimmer2(isShow: isLoading);
                      },
                    )
                  ],
                ),
              ),
            ],
          ).paddingOnly(top: 16.h, right: 16.w, left: 16.w, bottom: 12.h),
          1.divider,
          _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 = profile.responseId != currentUserId;

    return CustomButton(
      icon: canSwitch ? AppAssets.switch_user : AppAssets.add_family,
      text: canSwitch ? LocaleKeys.switchAccount.tr() : LocaleKeys.addANewFamilyMember.tr(),
      onPressed: canSwitch ? () => onFamilySwitchPress(profile) : onAddFamilyMemberPress,
      backgroundColor: canSwitch ? AppColors.secondaryLightRedColor : AppColors.primaryRedColor,
      borderColor: canSwitch ? AppColors.secondaryLightRedColor : AppColors.primaryRedColor,
      textColor: canSwitch ? AppColors.primaryRedColor : AppColors.whiteColor,
      iconColor: canSwitch ? AppColors.primaryRedColor : AppColors.whiteColor,
      height: isFoldable ? 50.h : 40.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 == profile.responseId;

    return CustomButton(
      icon: AppAssets.switch_user,
      text: canSwitchBack ? LocaleKeys.switchBackFamilyFile.tr() : LocaleKeys.switchLogin.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 ? () => onFamilySwitchPress(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),
//
}
