import 'package:clarity_flutter/clarity_flutter.dart';
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_state.dart';
import 'package:hmg_patient_app_new/core/common_models/nationality_country_model.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/date_util.dart';
import 'package:hmg_patient_app_new/core/utils/size_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/insurance/insurance_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/insurance/widgets/patient_insurance_card.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/appbar/app_bar_widget.dart';
import 'package:hmg_patient_app_new/widgets/bottomsheet/generic_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/dropdown/dropdown_widget.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:provider/provider.dart';

class RegisterNewStep2 extends StatefulWidget {
  RegisterNewStep2({Key? key}) : super(key: key);

  @override
  _RegisterNew createState() => _RegisterNew();
}

class _RegisterNew extends State<RegisterNewStep2> {
  AuthenticationViewModel? authVM;
  InsuranceViewModel? insuranceVM;

  @override
  void initState() {
    Clarity.setCurrentScreenName('Registration Step 2 Screen');
    super.initState();
    authVM = context.read<AuthenticationViewModel>();
    insuranceVM = context.read<InsuranceViewModel>();

    // Clear errors when entering the page
    WidgetsBinding.instance.addPostFrameCallback((_) {
      authVM?.clearAllStep2FieldErrors();
    });
    if (!authVM!.isUserFromUAE()) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        insuranceVM?.setIsInsuranceDataToBeLoaded(true);
        insuranceVM?.initInsuranceProvider();
      });
    }
  }

  @override
  void dispose() {
    // Clear errors when leaving the page
    WidgetsBinding.instance.addPostFrameCallback((_) {
      authVM?.clearAllStep2FieldErrors();
    });
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    AppState appState = getIt.get<AppState>();
    var name = authVM!.isUserFromUAE()
        ? ""
        : appState.getLanguageCode() == "en"
            ? ("${(appState.getNHICUserData.firstNameEn ?? '').toUpperCase()} ${(appState.getNHICUserData.lastNameEn ?? '').toUpperCase()}").trim()
            : ("${(appState.getNHICUserData.firstNameAr ?? '').toUpperCase()} ${(appState.getNHICUserData.lastNameAr ?? '').toUpperCase()}").trim();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      appBar: CustomAppBar(
        onBackPressed: () {
          Navigator.of(context).pop();
          // authVM!.clearDefaultInputValues();
          authVM!.clearEmailInput();
        },
        onLanguageChanged: (lang) {},
        hideLogoAndLang: true,
      ),
      bottomSheet: Container(
        // height: 200.h,
        width: MediaQuery.of(context).size.width,
        decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
          color: AppColors.whiteColor,
          customBorder: BorderRadius.only(topLeft: Radius.circular(24), topRight: Radius.circular(24)),
          hasShadow: true,
        ),
        child: Row(
          children: [
            Expanded(
              child: CustomButton(
                text: LocaleKeys.cancel.tr(),
                icon: AppAssets.cancel,
                onPressed: () {
                  Navigator.of(context).pop();
                  // authVM!.clearDefaultInputValues();
                },
                backgroundColor: AppColors.secondaryLightRedColor,
                borderColor: AppColors.secondaryLightRedColor,
                textColor: AppColors.primaryRedColor,
                iconColor: AppColors.primaryRedColor,
              ),
            ),
            SizedBox(width: 16.w),
            Expanded(
              child: CustomButton(
                backgroundColor: AppColors.primaryRedColor,
                borderColor: AppColors.primaryRedColor,
                textColor: AppColors.whiteColor,
                text: LocaleKeys.confirm.tr(),
                icon: AppAssets.confirm,
                iconColor: AppColors.whiteColor,
                onPressed: () {
                  // Unfocus keyboard
                  FocusScope.of(context).unfocus();

                  // For UAE users, validate the form first
                  if (appState.getUserRegistrationPayload.zipCode != CountryEnum.saudiArabia.countryCode) {
                    // Use ViewModel validation method
                    if (authVM!.validateRegistrationStep2Form()) {
                      showModel(context: context);
                    }
                  } else {
                    // For Saudi users, no validation needed, show email modal directly
                    showModel(context: context);
                  }
                },
              ),
            )
          ],
        ).paddingAll(16.h),
      ),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        behavior: HitTestBehavior.translucent, // Ensures taps on empty space are detected
        child: SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: SingleChildScrollView(
            reverse: false,
            padding: EdgeInsets.only(left: 24.w, right: 24.w, top: 0.h),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                LocaleKeys.personalDetailsVerification.tr(context: context).toText26(color: AppColors.textColor, isBold: true, letterSpacing: -2),
                SizedBox(height: 24.h),

                // Insurance Card Section
                Consumer<InsuranceViewModel>(
                  builder: (context, insuranceVM, child) {
                    // Only show if insurance data is available and not loading
                    if (!insuranceVM.isInsuranceLoading && insuranceVM.patientInsuranceList.isNotEmpty) {
                      return Column(
                        children: [
                          PatientInsuranceCard(
                            insuranceCardDetailsModel: insuranceVM.patientInsuranceList.first,
                            isInsuranceExpired: DateTime.now().isAfter(
                              DateUtil.convertStringToDate(insuranceVM.patientInsuranceList.first.cardValidTo),
                            ),
                          ),
                          SizedBox(height: 24.h),
                        ],
                      );
                    }
                    // Don't show anything if loading or no data
                    return SizedBox.shrink();
                  },
                ),

                // Form Container with Error Border
                Selector<AuthenticationViewModel, bool>(
                  selector: (_, model) => model.hasRegistrationStep2FormError,
                  builder: (context, hasError, child) {
                    return Container(
                      decoration: BoxDecoration(
                        color: AppColors.whiteColor,
                        borderRadius: BorderRadius.circular(24),
                        border: Border.all(
                          color: hasError ? AppColors.primaryRedBorderColor : Colors.transparent,
                          width: 1,
                        ),
                      ),
                      padding: EdgeInsets.only(left: 16.h, right: 16.h),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          TextInputWidget(
                            labelText: authVM!.isUserFromUAE() ? LocaleKeys.fullName.tr(context: context) : LocaleKeys.name.tr(context: context),
                            hintText: authVM!.isUserFromUAE() ? LocaleKeys.enterNameHere.tr(context: context) : (name),
                            controller: authVM!.isUserFromUAE() ? authVM!.nameController : null,
                            isEnable: true,
                            prefix: null,
                            isAllowRadius: false,
                            isBorderAllowed: false,
                            // hintColor: Color(0xff898A8D),
                            keyboardType: TextInputType.text,
                            onSubmitted: (value) {
                              FocusScope.of(context).unfocus();
                            },
                            onChange: (value) {
                              authVM!.clearNameError();
                            },
                            isAllowLeadingIcon: true,
                            isReadOnly: authVM!.isUserFromUAE() ? false : true,
                            leadingIcon: AppAssets.user_circle,
                            labelColor: AppColors.textColor,
                          ).paddingSymmetrical(0.h, 8.h),
                          // Show error message if exists
                          if (authVM!.isUserFromUAE() && authVM!.nameError != null)
                            Padding(
                              padding: EdgeInsets.only(left: 0.w, top: 4.h, bottom: 4.h, right: 16.w),
                              child: Text(
                                authVM!.nameError!,
                                style: TextStyle(
                                  color: AppColors.primaryRedColor,
                                  fontSize: 12.f,
                                ),
                              ),
                            ),
                          Divider(height: 1.h, color: AppColors.greyColor),
                          TextInputWidget(
                                  labelText: LocaleKeys.nationalIdNumber.tr(context: context),
                                  hintText: authVM!.isUserFromUAE() ? appState.getUserRegistrationPayload.patientIdentificationId.toString() : (appState.getNHICUserData.idNumber ?? ""),
                                  controller: null,
                                  isEnable: true,
                                  prefix: null,
                                  isAllowRadius: false,
                                  isBorderAllowed: false,
                                  isAllowLeadingIcon: true,
                                  isReadOnly: true,
                                  labelColor: AppColors.textColor,
                                  leadingIcon: AppAssets.student_card)
                              .paddingSymmetrical(0.h, 8.h),
                          Divider(height: 1, color: AppColors.greyColor),
                          authVM!.isUserFromUAE()
                              ? Selector<AuthenticationViewModel, GenderTypeEnum?>(
                                  selector: (_, authViewModel) => authViewModel.genderType,
                                  shouldRebuild: (previous, next) => previous != next,
                                  builder: (context, genderType, child) {
                                    final authVM = context.read<AuthenticationViewModel>();
                                    return DropdownWidget(
                                      labelText: LocaleKeys.gender.tr(context: context),
                                      hintText: LocaleKeys.malE.tr(context: context),
                                      isEnable: true,
                                      dropdownItems: GenderTypeEnum.values.map((e) => appState.isArabic() ? e.typeAr : e.type).toList(),
                                      selectedValue: genderType != null ? (appState.isArabic() ? genderType.typeAr : genderType.type) : "",
                                      onChange: authVM.onGenderChange,
                                      isBorderAllowed: false,
                                      hasSelectionCustomIcon: true,
                                      isAllowRadius: false,
                                      labelColor: AppColors.textColor,
                                      padding: EdgeInsets.only(top: 8.h, bottom: 8.h, left: 0, right: 0),
                                      selectionCustomIcon: AppAssets.arrow_down,
                                      leadingIcon: AppAssets.user_full,
                                    ).withVerticalPadding(8);
                                  })
                              : TextInputWidget(
                                      labelText: LocaleKeys.gender.tr(context: context),
                                      hintText: (appState.getNHICUserData.gender ?? ""),
                                      controller: null,
                                      isEnable: true,
                                      prefix: null,
                                      isAllowRadius: false,
                                      isBorderAllowed: false,
                                      isAllowLeadingIcon: true,
                                      isReadOnly: authVM!.isUserFromUAE() ? false : true,
                                      leadingIcon: AppAssets.user_full,
                                      labelColor: AppColors.textColor,
                                      onChange: (value) {})
                                  .paddingSymmetrical(0.h, 8.h),
                          // Show gender error message if exists (for UAE users)
                          if (authVM!.isUserFromUAE() && authVM!.genderError != null)
                            Padding(
                              padding: EdgeInsets.only(left: 0.w, top: 4.h, bottom: 4.h, right: 16.w),
                              child: Text(
                                authVM!.genderError!,
                                style: TextStyle(
                                  color: AppColors.primaryRedColor,
                                  fontSize: 12.f,
                                ),
                              ),
                            ),
                          Divider(height: 1, color: AppColors.greyColor),
                          authVM!.isUserFromUAE()
                              ? Selector<AuthenticationViewModel, MaritalStatusTypeEnum?>(
                                  selector: (_, authViewModel) => authViewModel.maritalStatus,
                                  shouldRebuild: (previous, next) => previous != next,
                                  builder: (context, maritalStatus, child) {
                                    final authVM = context.read<AuthenticationViewModel>(); // For onChange
                                    return DropdownWidget(
                                      labelText: LocaleKeys.maritalStatus.tr(context: context),
                                      hintText: LocaleKeys.married.tr(context: context),
                                      isEnable: true,
                                      dropdownItems: MaritalStatusTypeEnum.values.map((e) => appState.isArabic() ? e.typeAr : e.type).toList(),
                                      selectedValue: maritalStatus != null ? (appState.isArabic() ? maritalStatus.typeAr : maritalStatus.type) : "",
                                      onChange: authVM.onMaritalStatusChange,
                                      isBorderAllowed: false,
                                      hasSelectionCustomIcon: true,
                                      isAllowRadius: false,
                                      labelColor: AppColors.textColor,
                                      padding: EdgeInsets.only(top: 8.h, bottom: 8.h, left: 0, right: 0),
                                      selectionCustomIcon: AppAssets.arrow_down,
                                      leadingIcon: AppAssets.smart_phone,
                                    ).withVerticalPadding(8);
                                  },
                                )
                              : TextInputWidget(
                                      labelText: LocaleKeys.maritalStatus.tr(context: context),
                                      hintText: appState.isArabic()
                                          ? (MaritalStatusTypeExtension.fromValue(appState.getNHICUserData.maritalStatusCode)?.typeAr ?? '')
                                          : (MaritalStatusTypeExtension.fromValue(appState.getNHICUserData.maritalStatusCode)?.type ?? ''),
                                      isEnable: true,
                                      prefix: null,
                                      isAllowRadius: false,
                                      isBorderAllowed: false,
                                      isAllowLeadingIcon: true,
                                      isReadOnly: true,
                                      labelColor: AppColors.textColor,
                                      leadingIcon: AppAssets.smart_phone,
                                      onChange: (value) {})
                                  .paddingSymmetrical(0.h, 8.h),
                          // Show marital status error message if exists (for UAE users)
                          if (authVM!.isUserFromUAE() && authVM!.maritalStatusError != null)
                            Padding(
                              padding: EdgeInsets.only(left: 0.w, top: 4.h, bottom: 4.h, right: 16.w),
                              child: Text(
                                authVM!.maritalStatusError!,
                                style: TextStyle(
                                  color: AppColors.primaryRedColor,
                                  fontSize: 12.f,
                                ),
                              ),
                            ),
                          Divider(height: 1.h, color: AppColors.greyColor),
                          authVM!.isUserFromUAE()
                              ? Selector<AuthenticationViewModel, ({List<NationalityCountries>? countriesList, NationalityCountries? selectedCountry, bool isArabic})>(
                                  selector: (context, authViewModel) {
                                    final appState = getIt.get<AppState>();
                                    return (
                                      countriesList: authViewModel.countriesList,
                                      selectedCountry: authViewModel.pickedCountryByUAEUser,
                                      isArabic: appState.isArabic(),
                                    );
                                  },
                                  shouldRebuild: (previous, next) =>
                                      previous.countriesList != next.countriesList || previous.selectedCountry != next.selectedCountry || previous.isArabic != next.isArabic,
                                  builder: (context, data, child) {
                                    final authVM = context.read<AuthenticationViewModel>();
                                    return DropdownWidget(
                                      labelText: LocaleKeys.country.tr(context: context),
                                      hintText: LocaleKeys.uae.tr(context: context),
                                      isEnable: true,
                                      dropdownItems: (data.countriesList ?? []).map((e) => data.isArabic ? e.nameN ?? "" : e.name ?? "").toList(),
                                      selectedValue: data.selectedCountry != null
                                          ? data.isArabic
                                              ? data.selectedCountry!.nameN ?? ""
                                              : data.selectedCountry!.name ?? ""
                                          : "",
                                      onChange: authVM.onUAEUserCountrySelection,
                                      isBorderAllowed: false,
                                      hasSelectionCustomIcon: true,
                                      labelColor: AppColors.textColor,
                                      isAllowRadius: false,
                                      padding: EdgeInsets.only(top: 8.h, bottom: 8.h, left: 0, right: 0),
                                      selectionCustomIcon: AppAssets.arrow_down,
                                      leadingIcon: AppAssets.globe,
                                    ).withVerticalPadding(8.h);
                                  },
                                )
                              : TextInputWidget(
                                      labelText: LocaleKeys.nationality.tr(context: context),
                                      hintText: appState.isArabic()
                                          ? (authVM!.countriesList!.firstWhere((e) => e.id == (appState.getNHICUserData.nationalityCode ?? ""), orElse: () => NationalityCountries()).nameN ?? "")
                                          : (authVM!.countriesList!.firstWhere((e) => e.id == (appState.getNHICUserData.nationalityCode ?? ""), orElse: () => NationalityCountries()).name ?? ""),
                                      isEnable: true,
                                      prefix: null,
                                      isAllowRadius: false,
                                      isBorderAllowed: false,
                                      isAllowLeadingIcon: true,
                                      isReadOnly: true,
                                      labelColor: AppColors.textColor,
                                      leadingIcon: AppAssets.globe,
                                      onChange: (value) {})
                                  .paddingSymmetrical(0.h, 8.h),
                          // Show country error message if exists (for UAE users)
                          if (authVM!.isUserFromUAE() && authVM!.countryError != null)
                            Padding(
                              padding: EdgeInsets.only(left: 0.w, top: 4.h, bottom: 4.h, right: 16.w),
                              child: Text(
                                authVM!.countryError!,
                                style: TextStyle(
                                  color: AppColors.primaryRedColor,
                                  fontSize: 12.f,
                                ),
                              ),
                            ),
                          Divider(
                            height: 1,
                            color: AppColors.greyColor,
                          ),
                          TextInputWidget(
                                  labelText: LocaleKeys.mobileNumber.tr(context: context),
                                  hintText: appState.getUserRegistrationPayload.patientMobileNumber.toString(),
                                  controller: null,
                                  isEnable: false,
                                  prefix: null,
                                  isAllowRadius: false,
                                  isBorderAllowed: false,
                                  isAllowLeadingIcon: true,
                                  labelColor: AppColors.textColor,
                                  isReadOnly: true,
                                  leadingIcon: AppAssets.call)
                              .paddingSymmetrical(0.h, 8.h),
                          Divider(
                            height: 1.h,
                            color: AppColors.greyColor,
                          ),
                          TextInputWidget(
                            labelText: LocaleKeys.dob.tr(context: context),
                            hintText: authVM!.isUserFromUAE() ? (appState.getUserRegistrationPayload.dob ?? '') : (appState.getNHICUserData.dateOfBirth ?? ""),
                            controller: authVM!.isUserFromUAE() ? authVM!.dobController : null,
                            isEnable: false,
                            prefix: null,
                            isBorderAllowed: false,
                            isAllowLeadingIcon: true,
                            isReadOnly: true,
                            labelColor: AppColors.textColor,
                            leadingIcon: AppAssets.birthday_cake,
                            selectionType: null,
                          ).paddingSymmetrical(0.h, 8.h),
                        ],
                      ),
                    );
                  },
                ),
                SizedBox(height: 50.h),
                // Row(
                //   children: [
                //     Expanded(
                //       child: CustomButton(
                //         text: LocaleKeys.cancel.tr(context: context),
                //         icon: AppAssets.cancel,
                //         onPressed: () {
                //           Navigator.of(context).pop();
                //           // authVM!.clearDefaultInputValues();
                //         },
                //         backgroundColor: AppColors.secondaryLightRedColor,
                //         borderColor: AppColors.secondaryLightRedColor,
                //         textColor: AppColors.primaryRedColor,
                //         iconColor: AppColors.primaryRedColor,
                //       ),
                //     ),
                //     SizedBox(width: 16.w),
                //     Expanded(
                //       child: CustomButton(
                //         backgroundColor: AppColors.primaryRedColor,
                //         borderColor: AppColors.primaryRedColor,
                //         textColor: AppColors.whiteColor,
                //         text: LocaleKeys.confirm.tr(context: context),
                //         icon: AppAssets.confirm,
                //         iconColor: AppColors.whiteColor,
                //         onPressed: () {
                //           if (appState.getUserRegistrationPayload.zipCode != CountryEnum.saudiArabia.countryCode) {
                //             if (ValidationUtils.validateUaeRegistration(
                //                 name: authVM!.nameController.text,
                //                 gender: authVM!.genderType,
                //                 country: authVM!.pickedCountryByUAEUser,
                //                 maritalStatus: authVM!.maritalStatus,
                //                 onOkPress: () {
                //                   Navigator.of(context).pop();
                //                 })) {
                //               showModel(context: context);
                //             }
                //           } else {
                //             showModel(context: context);
                //           }
                //         },
                //       ),
                //     )
                //   ],
                // ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void showModel({required BuildContext context}) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      isDismissible: false,
      backgroundColor: Colors.transparent,
      builder: (bottomSheetContext) => Padding(
        padding: EdgeInsets.only(bottom: MediaQuery.of(bottomSheetContext).viewInsets.bottom),
        child: SingleChildScrollView(
          child: GenericBottomSheet(
            textController: authVM!.emailController,
            isForEmail: true,
            buttons: [
              Padding(
                padding: const EdgeInsets.only(bottom: 10),
                child: CustomButton(
                    text: LocaleKeys.submit.tr(context: context),
                    onPressed: () {
                      // Use ViewModel validation method
                      if (authVM!.validateEmail()) {
                        authVM!.onRegistrationComplete();
                      } else {
                        // Show error in a dialog
                        if (authVM!.emailError != null) {
                          // dialogService can be used here if needed
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text(authVM!.emailError!)),
                          );
                        }
                      }
                    },
                    backgroundColor: AppColors.bgGreenColor,
                    borderColor: AppColors.bgGreenColor,
                    textColor: AppColors.whiteColor),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
