import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.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_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';
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/blood_donation/blood_donation_view_model.dart';
import 'package:hmg_patient_app_new/features/blood_donation/models/blood_group_hospitals_model.dart';
import 'package:hmg_patient_app_new/features/blood_donation/widgets/hospital_selection.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/blood_donation/widgets/select_blood_group_widget.dart';
import 'package:hmg_patient_app_new/presentation/blood_donation/widgets/select_city_widget.dart';
import 'package:hmg_patient_app_new/presentation/blood_donation/widgets/select_gender_widget.dart';
import 'package:hmg_patient_app_new/services/dialog_service.dart';
import 'package:hmg_patient_app_new/theme/colors.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/common_bottom_sheet.dart';
import 'package:lottie/lottie.dart';
import 'package:provider/provider.dart';

class BloodDonationPage extends StatefulWidget {
  BloodDonationPage({super.key});

  @override
  State<BloodDonationPage> createState() => _BloodDonationPageState();
}

class _BloodDonationPageState extends State<BloodDonationPage> {
  late AppState appState;

  @override
  void initState() {
    super.initState();
    Future.microtask(() => getIt.get<BloodDonationViewModel>().fetchAllData());
  }

  @override
  Widget build(BuildContext context) {
    appState = getIt<AppState>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Consumer<BloodDonationViewModel>(builder: (context, bloodDonationVM, child) {
        return Column(
          children: [
            Expanded(
              child: CollapsingListView(
                title: LocaleKeys.bloodDonation.tr(),
                trailing: CustomButton(
                    text: LocaleKeys.book.tr(context: context),
                    onPressed: () {
                      if (bloodDonationVM.isUserAuthanticated()) {
                        bloodDonationVM.fetchHospitalsList().then((value) {
                          showCommonBottomSheetWithoutHeight(context, title: LocaleKeys.selectHospital.tr(context: context), isDismissible: false,
                              child: Consumer<BloodDonationViewModel>(builder: (_, data, __) {
                            return HospitalBottomSheetBodySelection(
                              isHideTitle: true,
                              onUserHospitalSelection: (BdGetProjectsHaveBdClinic userChoice) {
                                bloodDonationVM.getFreeBloodDonationSlots(request: {"ClinicID": 134, "ProjectID": userChoice.projectId});
                              },
                            );
                          }), callBackFunc: () {});
                        });
                      } else {
                        return showCommonBottomSheetWithoutHeight(
                          context,
                          title: LocaleKeys.notice.tr(context: context),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Lottie.asset(AppAnimations.errorAnimation,
                                  repeat: true, reverse: false, frameRate: FrameRate(60), width: 100.h, height: 100.h, fit: BoxFit.fill),
                              SizedBox(height: 8.h),
                              (LocaleKeys.loginToUseService.tr()).toText16(color: AppColors.blackColor),
                              SizedBox(height: 16.h),
                              Row(
                                children: [
                                  Expanded(
                                    child: CustomButton(
                                      text: LocaleKeys.cancel.tr(),
                                      onPressed: () {
                                        Navigator.of(context).pop();
                                      },
                                      backgroundColor: AppColors.secondaryLightRedColor,
                                      borderColor: AppColors.secondaryLightRedColor,
                                      textColor: AppColors.primaryRedColor,
                                      icon: AppAssets.cancel,
                                      iconColor: AppColors.primaryRedColor,
                                    ),
                                  ),
                                  SizedBox(width: 8.h),
                                  Expanded(
                                    child: CustomButton(
                                      text: LocaleKeys.confirm.tr(),
                                      onPressed: () async {
                                        Navigator.of(context).pop();
                                        // Navigator.pushAndRemoveUntil(context, CustomPageRoute(page: LandingNavigation()), (r) => false);
                                        await getIt<AuthenticationViewModel>().onLoginPressed();
                                      },
                                      backgroundColor: AppColors.bgGreenColor,
                                      borderColor: AppColors.bgGreenColor,
                                      textColor: Colors.white,
                                      icon: AppAssets.confirm,
                                    ),
                                  ),
                                ],
                              ),
                              SizedBox(height: 16.h),
                            ],
                          ).center,
                          callBackFunc: () {},
                          isFullScreen: false,
                          isCloseButtonVisible: true,
                        );
                      }
                    },
                    backgroundColor: AppColors.bgRedLightColor,
                    borderColor: AppColors.bgRedLightColor,
                    textColor: AppColors.primaryRedColor,
                    isDisabled: !Utils.havePrivilege(117),
                    padding: EdgeInsetsGeometry.symmetric(vertical: 0.h, horizontal: 20.h)),
                child: Padding(
                  padding: EdgeInsets.all(24.w),
                  child: SingleChildScrollView(
                    child: Container(
                      decoration:
                          RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: false),
                      child: Padding(
                        padding: EdgeInsets.all(16.h),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    Utils.buildSvgWithAssets(icon: AppAssets.select_city_icon, width: 40.h, height: 40.h),
                                    SizedBox(width: 12.w),
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        LocaleKeys.city.tr().toText16(color: AppColors.textColor, isBold: true),
                                        (appState.isArabic()
                                                ? (bloodDonationVM.selectedCity?.descriptionN ?? LocaleKeys.selectBloodDonationCity.tr())
                                                : bloodDonationVM.selectedCity?.description ??
                                                    LocaleKeys.selectBloodDonationCity.tr(context: context))
                                            .toText14(color: AppColors.greyTextColor, isBold: true),
                                      ],
                                    ),
                                  ],
                                ),
                                Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, width: 25.h, height: 25.h),
                              ],
                            ).onPress(() async {
                              showCommonBottomSheetWithoutHeight(context,
                                  title: LocaleKeys.selectCity.tr(context: context),
                                  isDismissible: true,
                                  child: SelectCityWidget(bloodDonationViewModel: bloodDonationVM),
                                  callBackFunc: () {});
                            }),
                            SizedBox(height: 16.h),
                            Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h),
                            SizedBox(height: 16.h),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    Utils.buildSvgWithAssets(icon: AppAssets.genderInputIcon, width: 40.h, height: 40.h),
                                    SizedBox(width: 12.w),
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        LocaleKeys.gender.tr().toText16(color: AppColors.textColor, isBold: true),
                                        (appState.isArabic()
                                                ? (bloodDonationVM.selectedGender?.typeAr ?? LocaleKeys.selectBloodDonationGender.tr())
                                                : bloodDonationVM.selectedGender?.type ?? LocaleKeys.selectBloodDonationGender.tr(context: context))
                                            .toText14(color: AppColors.greyTextColor, isBold: true),
                                      ],
                                    ),
                                  ],
                                ),
                                Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, width: 25.h, height: 25.h),
                              ],
                            ).onPress(() {
                              showCommonBottomSheetWithoutHeight(context,
                                  title: LocaleKeys.selectGender.tr(context: context),
                                  isDismissible: true,
                                  child: SelectGenderWidget(isArabic: appState.isArabic(), bloodDonationViewModel: bloodDonationVM),
                                  callBackFunc: () {});
                            }),
                            SizedBox(height: 16.h),
                            Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h),
                            SizedBox(height: 16.h),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Row(
                                  children: [
                                    Utils.buildSvgWithAssets(icon: AppAssets.bloodType, width: 40.h, height: 40.h),
                                    SizedBox(width: 12.w),
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        LocaleKeys.bloodType.tr().toText16(color: AppColors.textColor, isBold: true),
                                        // bloodDonationVM.selectedBloodType?.toText14(color: AppColors.greyTextColor, isBold: true),
                                        (appState.isArabic()
                                                ? (bloodDonationVM.selectedBloodType ?? LocaleKeys.selectBloodType.tr())
                                                : bloodDonationVM.selectedBloodType ?? LocaleKeys.selectBloodType.tr(context: context))
                                            .toText14(color: AppColors.greyTextColor, isBold: true)
                                      ],
                                    ),
                                  ],
                                ),
                                Utils.buildSvgWithAssets(icon: AppAssets.arrow_down, width: 25.h, height: 25.h),
                              ],
                            ).onPress(() {
                              showCommonBottomSheetWithoutHeight(context,
                                  title: LocaleKeys.selectBloodGroup.tr(context: context),
                                  isDismissible: true,
                                  child: SelectBloodGroupWidget(isArabic: appState.isArabic(), bloodDonationViewModel: bloodDonationVM),
                                  callBackFunc: () {});
                            }),
                            SizedBox(height: 24.h),
                            Container(
                              padding: EdgeInsets.all(16.h),
                              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                color: AppColors.bgRedLightColor.withValues(alpha: 0.1),
                                borderRadius: 12.r,
                                hasShadow: false,
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    children: [
                                      Container(
                                        padding: EdgeInsets.all(8.h),
                                        decoration: BoxDecoration(
                                          color: AppColors.primaryRedColor.withValues(alpha: 0.1),
                                          borderRadius: BorderRadius.circular(8.r),
                                        ),
                                        child: Utils.buildSvgWithAssets(
                                          icon: AppAssets.blood_icon,
                                          width: 20.h,
                                          height: 20.h,
                                          iconColor: AppColors.primaryRedColor,
                                        ),
                                      ),
                                      SizedBox(width: 12.w),
                                      Expanded(
                                        child: LocaleKeys.aboutBloodDonation.tr(context: context).toText16(
                                              color: AppColors.primaryRedColor,
                                              isBold: true,
                                            ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(height: 12.h),
                                  LocaleKeys.bloodDonationDescription.tr(context: context).toText14(
                                        color: AppColors.greyTextColor,
                                        isBold: true,
                                      ),
                                  SizedBox(height: 12.h),
                                  Row(
                                    children: [
                                      Container(
                                        width: 4.w,
                                        height: 4.h,
                                        decoration: BoxDecoration(
                                          color: AppColors.primaryRedColor,
                                          shape: BoxShape.circle,
                                        ),
                                      ),
                                      SizedBox(width: 8.w),
                                      Expanded(
                                        child: LocaleKeys.bloodDonationBenefit1.tr(context: context).toText13(
                                              color: AppColors.textColor,
                                              isBold: true,
                                            ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(height: 8.h),
                                  Row(
                                    children: [
                                      Container(
                                        width: 4.w,
                                        height: 4.h,
                                        decoration: BoxDecoration(
                                          color: AppColors.primaryRedColor,
                                          shape: BoxShape.circle,
                                        ),
                                      ),
                                      SizedBox(width: 8.w),
                                      Expanded(
                                        child: LocaleKeys.bloodDonationBenefit2.tr(context: context).toText13(
                                              color: AppColors.textColor,
                                              isBold: true,
                                            ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(height: 8.h),
                                  Row(
                                    children: [
                                      Container(
                                        width: 4.w,
                                        height: 4.h,
                                        decoration: BoxDecoration(
                                          color: AppColors.primaryRedColor,
                                          shape: BoxShape.circle,
                                        ),
                                      ),
                                      SizedBox(width: 8.w),
                                      Expanded(
                                        child: LocaleKeys.bloodDonationBenefit3.tr(context: context).toText13(
                                              color: AppColors.textColor,
                                              isBold: true,
                                            ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
            Container(
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 24.r, hasShadow: true),
              child: SizedBox(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    GestureDetector(
                      onTap: bloodDonationVM.onTermAccepted,
                      child: Row(
                        children: [
                          Selector<BloodDonationViewModel, bool>(
                            selector: (_, viewModel) => viewModel.isTermsAccepted,
                            shouldRebuild: (previous, next) => previous != next,
                            builder: (context, isTermsAccepted, child) {
                              return AnimatedContainer(
                                duration: const Duration(milliseconds: 200),
                                height: 24.h,
                                width: 24.h,
                                decoration: BoxDecoration(
                                  color: isTermsAccepted ? AppColors.primaryRedColor : Colors.transparent,
                                  borderRadius: BorderRadius.circular(6),
                                  border: Border.all(color: isTermsAccepted ? AppColors.primaryRedBorderColor : AppColors.greyColor, width: 2.h),
                                ),
                                child: isTermsAccepted ? Icon(Icons.check, size: 16.f, color: Colors.white) : null,
                              );
                            },
                          ),
                          SizedBox(width: 12.h),
                          Row(
                            children: [
                              Text(
                                "${LocaleKeys.iAcceptThe.tr()} ",
                                style: context.dynamicTextStyle(fontSize: 14.f, fontWeight: FontWeight.w600, color: Color(0xFF2E3039)),
                              ),
                              GestureDetector(
                                onTap: () {
                                  // Navigate to terms and conditions page
                                  // Navigator.of(context).pushNamed('/terms');
                                  appState.isArabic()
                                      ? Utils.openWebView(
                                          url: AppUrls.hmgTermsUrlAr,
                                        )
                                      : Utils.openWebView(
                                          url: AppUrls.hmgTermsUrlEn,
                                        );
                                },
                                child: Text(
                                  LocaleKeys.termsConditoins.tr(),
                                  style: context.dynamicTextStyle(
                                    fontSize: 14.f,
                                    fontWeight: FontWeight.w600,
                                    color: AppColors.primaryRedColor,
                                    decoration: TextDecoration.underline,
                                    decorationColor: AppColors.primaryRedBorderColor,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          // Expanded(
                          //   child: Text(
                          //     LocaleKeys.iAcceptTermsConditions.tr().split("the").first,
                          //     style: context.dynamicTextStyle(fontSize: 14.fSize, isBold: true, color: Color(0xFF2E3039)),
                          //   ),
                          // ),
                        ],
                      ),
                    ).paddingOnly(left: 16.h, right: 16.h, top: 24.h),
                    CustomButton(
                      text: LocaleKeys.save.tr(),
                      onPressed: () async {
                        DialogService dialogService = getIt.get<DialogService>();
                        if (await bloodDonationVM.validateSelections()) {
                          if (bloodDonationVM.isUserAuthanticated()) {
                            bloodDonationVM.updateBloodGroup();
                          } else {
                            return showCommonBottomSheetWithoutHeight(
                              context,
                              title: LocaleKeys.notice.tr(context: context),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Lottie.asset(AppAnimations.errorAnimation,
                                      repeat: true, reverse: false, frameRate: FrameRate(60), width: 100.h, height: 100.h, fit: BoxFit.fill),
                                  SizedBox(height: 8.h),
                                  (LocaleKeys.loginToUseService.tr()).toText16(color: AppColors.blackColor),
                                  SizedBox(height: 16.h),
                                  Row(
                                    children: [
                                      Expanded(
                                        child: CustomButton(
                                          text: LocaleKeys.cancel.tr(),
                                          onPressed: () {
                                            Navigator.of(context).pop();
                                          },
                                          backgroundColor: AppColors.secondaryLightRedColor,
                                          borderColor: AppColors.secondaryLightRedColor,
                                          textColor: AppColors.primaryRedColor,
                                          icon: AppAssets.cancel,
                                          iconColor: AppColors.primaryRedColor,
                                        ),
                                      ),
                                      SizedBox(width: 8.h),
                                      Expanded(
                                        child: CustomButton(
                                          text: LocaleKeys.confirm.tr(),
                                          onPressed: () async {
                                            Navigator.of(context).pop();
                                            // Navigator.pushAndRemoveUntil(context, CustomPageRoute(page: LandingNavigation()), (r) => false);
                                            await getIt<AuthenticationViewModel>().onLoginPressed();
                                          },
                                          backgroundColor: AppColors.bgGreenColor,
                                          borderColor: AppColors.bgGreenColor,
                                          textColor: Colors.white,
                                          icon: AppAssets.confirm,
                                        ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(height: 16.h),
                                ],
                              ).center,
                              callBackFunc: () {},
                              isFullScreen: false,
                              isCloseButtonVisible: true,
                            );
                          }
                        }
                      },
                      backgroundColor: AppColors.primaryRedColor,
                      borderColor: AppColors.primaryRedColor,
                      textColor: AppColors.whiteColor,
                      fontSize: 16.f,
                      isBold: true,
                      borderRadius: 12.r,
                      padding: EdgeInsets.symmetric(horizontal: 10.w),
                      height: 50.h,
                      iconSize: 18.h,
                    ).paddingSymmetrical(16.h, 24.h),
                  ],
                ),
              ),
            ),
          ],
        );
      }),
    );
  }
}
