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/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.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/services/dialog_service.dart';
import 'package:hmg_patient_app_new/services/navigation_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/custom_chip_widget.dart';

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

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

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

class _FamilyCardsState extends State<FamilyCards> {
  AppState appState = getIt<AppState>();

  @override
  Widget build(BuildContext context) {
    DialogService dialogService = getIt.get<DialogService>();
    if (widget.isRequestDesign) {
      return Column(
        children: [
          Row(
            children: [
              Utils.buildSvgWithAssets(icon: AppAssets.alertSquare),
              SizedBox(width: 8.h),
              "Who can view my medical file ?".needTranslation.toText14(color: AppColors.textColor, isUnderLine: true, weight: FontWeight.w500).onPress(() {
                dialogService.showFamilyBottomSheetWithoutHWithChild(
                  label: "Manage Family".needTranslation,
                  message: "",
                  child: manageFamily(),
                  onOkPressed: () {},
                );
              }),
              SizedBox(width: 4.h),
              Utils.buildSvgWithAssets(icon: AppAssets.arrowRight),
            ],
          ),
          SizedBox(height: 24.h),
          widget.profiles.where((profile) => profile.isRequestFromMySide ?? false).isEmpty
              ? Utils.getNoDataWidget(context)
              : ListView.builder(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  padding: EdgeInsets.zero,
                  itemCount: widget.profiles.where((profile) => profile.isRequestFromMySide ?? false).length,
                  itemBuilder: (context, index) {
                    final mySideProfiles = widget.profiles.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: [
                            CustomChipWidget(
                                height: 30.h,
                                chipType: ChipTypeEnum.alert,
                                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,
                                chipText: profile.statusDescription ?? "N/A",
                                iconAsset: null,
                                isShowBorder: false,
                                borderRadius: 8.h,
                                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: false, isCenter: false, maxlines: 1, weight: FontWeight.w600),
                              (getStatusTextByRequest(FamilyFileEnum.values.firstWhere((e) => e.toInt == profile.status), profile.isRequestFromMySide ?? false))
                                  .toText12(isBold: false, isCenter: false, maxLine: 1, fontWeight: FontWeight.w500, color: AppColors.greyTextColor),
                            ]),
                            SizedBox(height: 8.h),
                            CustomChipWidget(
                                height: 30.h,
                                chipType: ChipTypeEnum.alert,
                                backgroundColor: AppColors.lightGrayBGColor,
                                chipText: "Medical File: ${profile.responseId ?? "N/A"}",
                                iconAsset: null,
                                isShowBorder: false,
                                borderRadius: 8.h,
                                textColor: AppColors.textColor),
                          ],
                        ),
                      ),
                    );
                  },
                ),
          SizedBox(height: 20.h),
        ],
      );
    } else {
      return GridView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemCount: widget.profiles.length,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 10.h,
          mainAxisSpacing: 10.h,
          childAspectRatio: widget.isShowDetails ? 0.56.h : 0.65.h,
        ),
        padding: EdgeInsets.only(bottom: 20.h),
        itemBuilder: (context, index) {
          final profile = widget.profiles[index];
          final isActive = (profile.responseId == appState.getAuthenticatedUser()?.patientId);
          final isParentUser = appState.getAuthenticatedUser()?.isParentUser ?? false;
          final canSwitch = isParentUser || (!isParentUser && profile.responseId == appState.getSuperUserID);
          return Container(
            padding: EdgeInsets.symmetric(vertical: 15.h, horizontal: 15.h),
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24),
            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: [
                      Utils.buildImgWithAssets(
                          icon: profile.gender == null
                              ? AppAssets.dummy_user
                              : profile.gender == 1
                                  ? ((profile.age ?? 0) < 7 ? AppAssets.babyBoyImg : AppAssets.male_img)
                                  : (profile.age! < 7 ? AppAssets.babyGirlImg : AppAssets.femaleImg),
                          width: 80.h,
                          height: 78.h),
                      SizedBox(height: 8.h),
                      (profile.patientName ?? "Unknown").toText14(isBold: false, isCenter: true, maxlines: 1, weight: FontWeight.w600),
                      SizedBox(height: 8.h),
                      CustomChipWidget(
                          chipType: ChipTypeEnum.alert,
                          backgroundColor: AppColors.lightGrayBGColor,
                          chipText: "Relation:${profile.relationship ?? "N/A"}",
                          iconAsset: AppAssets.heart,
                          isShowBorder: false,
                          borderRadius: 8.h,
                          textColor: AppColors.textColor),
                      widget.isShowDetails ? SizedBox(height: 4.h) : SizedBox(),
                      widget.isShowDetails
                          ? CustomChipWidget(
                              chipType: ChipTypeEnum.alert,
                              backgroundColor: AppColors.lightGrayBGColor,
                              chipText: "Age:${profile.age ?? "N/A"} Years",
                              isShowBorder: false,
                              borderRadius: 8.h,
                              textColor: AppColors.textColor,
                            )
                          : SizedBox(),
                      widget.isShowDetails
                          ? SizedBox(height: 8.h)
                          : SizedBox(
                              height: 4.h,
                            ),
                      Spacer(),
                      CustomButton(
                        height: 40.h,
                        onPressed: () {
                          if (canSwitch) widget.onSelect(profile);
                        },
                        text: isActive ? "Active".needTranslation : "Switch".needTranslation,
                        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) ...[
                    Positioned(
                      top: 0,
                      right: 0,
                      child: Utils.buildSvgWithAssets(icon: AppAssets.deleteIcon).onPress(() {
                        if (!isActive) widget.onRemove(profile);
                      }),
                    ),
                  ],
                ],
              ),
            ),
          );
        },
      );
    }
  }

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

    return widget.profiles.where((profile) => !(profile.isRequestFromMySide ?? false)).isEmpty
        ? Utils.getNoDataWidget(context)
        : ListView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            padding: EdgeInsetsGeometry.zero,
            itemCount: widget.profiles.where((profile) => !(profile.isRequestFromMySide ?? false)).length,
            itemBuilder: (context, index) {
              final otherProfiles = widget.profiles.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: [
                      CustomChipWidget(
                        height: 30.h,
                        chipType: ChipTypeEnum.alert,
                        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,
                        chipText: profile.statusDescription ?? "N/A",
                        iconAsset: null,
                        isShowBorder: false,
                        borderRadius: 8.h,
                        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: false, isCenter: true, maxlines: 1, weight: FontWeight.w600),
                          (getStatusTextByRequest(FamilyFileEnum.values.firstWhere((e) => e.toInt == profile.status), profile.isRequestFromMySide ?? false)).toText14(
                            isBold: false,
                            isCenter: true,
                            maxlines: 1,
                            weight: FontWeight.w500,
                            color: AppColors.greyTextColor,
                          ),
                        ],
                      ),
                      SizedBox(height: 8.h),
                      CustomChipWidget(
                        height: 30.h,
                        chipType: ChipTypeEnum.alert,
                        backgroundColor: AppColors.lightGrayBGColor,
                        chipText: "Medical File: ${profile.patientId ?? "N/A".needTranslation}",
                        iconAsset: null,
                        isShowBorder: false,
                        borderRadius: 8.h,
                        textColor: AppColors.textColor,
                      ),
                      SizedBox(height: 16.h),
                      Row(
                        children: [
                          profile.status == FamilyFileEnum.active.toInt
                              ? SizedBox()
                              : Expanded(
                                  child: CustomButton(
                                    height: 40.h,
                                    text: LocaleKeys.confirm.tr(),
                                    onPressed: () {
                                      navigationService.pop();
                                      widget.onSelect(profile);
                                    },
                                    backgroundColor: AppColors.lightGreenButtonColor,
                                    borderColor: AppColors.lightGreenButtonColor,
                                    textColor: AppColors.textGreenColor,
                                    icon: null,
                                  ),
                                ),
                          profile.status == FamilyFileEnum.active.toInt ? SizedBox() : SizedBox(width: 8.h),
                          Expanded(
                            child: CustomButton(
                              height: 40.h,
                              text: profile.status == FamilyFileEnum.active.toInt ? LocaleKeys.removeMember.tr() : LocaleKeys.cancel.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 "${status.displayName} your request to be your family member".needTranslation;
        } else {
          return "can view your file".needTranslation;
        }
      case FamilyFileEnum.pending:
        if (isRequestFromMySide) {
          return "has a request ${status.displayName} to be your family member".needTranslation;
        } else {
          return "wants to add you as their family member".needTranslation;
        }
      case FamilyFileEnum.rejected:
        if (isRequestFromMySide) {
          return "${status.displayName} your request to be your family member".needTranslation;
        } else {
          return "${status.displayName} your family member request".needTranslation;
        }
      case FamilyFileEnum.inactive:
        return "Inactive".needTranslation;
      default:
        return "N/A".needTranslation;
    }
  }
}
