import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/gestures.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/dependencies.dart';
import 'package:hmg_patient_app_new/core/enums.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/core/utils/validation_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/authentication/widgets/otp_verification_screen.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/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' show CustomButton;
import 'package:hmg_patient_app_new/widgets/dropdown/country_dropdown_widget.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:provider/provider.dart';

class RegisterNew extends StatefulWidget {
  @override
  _RegisterNew createState() => _RegisterNew();
}

class _RegisterNew extends State<RegisterNew> {
  late FocusNode _nationalIdFocusNode;
  late FocusNode _dobFocusNode;

  @override
  void initState() {
    super.initState();
    _nationalIdFocusNode = FocusNode();
    _dobFocusNode = FocusNode();
  }

  @override
  void dispose() {
    _nationalIdFocusNode.dispose();
    _dobFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    AuthenticationViewModel authVm = context.read<AuthenticationViewModel>();

    return Scaffold(
        backgroundColor: AppColors.bgScaffoldColor,
        appBar: CustomAppBar(
          onBackPressed: () {
            Navigator.of(context).pop();
          },
          onLanguageChanged: (String value) {
            context.setLocale(value == 'en' ? Locale('en', 'US') : Locale('ar', 'SA'));
          },
        ),
        body: GestureDetector(
          onTap: () {
            // Dismiss keyboard and unfocus all input fields
            _nationalIdFocusNode.unfocus();
            _dobFocusNode.unfocus();
            FocusScope.of(context).unfocus();
          },
          child: ScrollConfiguration(
            behavior: ScrollConfiguration.of(context).copyWith(overscroll: false, physics: const ClampingScrollPhysics()),
            child: NotificationListener<OverscrollIndicatorNotification>(
              onNotification: (notification) {
                notification.disallowIndicator();
                return true;
              },
              child: SingleChildScrollView(
                physics: ClampingScrollPhysics(),
                padding: EdgeInsets.symmetric(horizontal: 24.h),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Utils.showLottie(context: context, assetPath: 'assets/animations/lottie/register.json', width: 200.h, height: 200.h, fit: BoxFit.cover, repeat: true),
                    SizedBox(height: 16.h),
                    LocaleKeys.prepareToElevate.tr().toText32(isBold: true),
                    SizedBox(height: 24.h),
                    Directionality(
                      textDirection: Directionality.of(context),
                      child: Container(
                        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(24)),
                        padding: EdgeInsets.symmetric(horizontal: 16.h),
                        child: Column(
                          children: [
                            CustomCountryDropdown(
                              countryList: CountryEnum.values,
                              onCountryChange: authVm.onCountryChange,
                              isRtl: Directionality.of(context) == TextDirection.LTR,
                            ).withVerticalPadding(8.h),
                            Divider(height: 1.h),
                            TextInputWidget(
                              labelText: LocaleKeys.nationalIdNumber.tr(),
                              hintText: "xxxxxxxxx",
                              controller: authVm.nationalIdController,
                              focusNode: _nationalIdFocusNode,
                              isEnable: true,
                              prefix: null,
                              isAllowRadius: true,
                              isBorderAllowed: false,
                              isAllowLeadingIcon: true,
                              autoFocus: true,
                              padding: EdgeInsets.symmetric(vertical: 8.h),
                              leadingIcon: AppAssets.student_card,
                            ).withVerticalPadding(8),
                            Divider(height: 1),
                            TextInputWidget(
                              labelText: LocaleKeys.dob.tr(),
                              hintText: "11 July, 1994",
                              controller: authVm.dobController,
                              focusNode: _dobFocusNode,
                              isEnable: true,
                              prefix: null,
                              isAllowRadius: true,
                              isBorderAllowed: false,
                              isAllowLeadingIcon: true,
                              padding: EdgeInsets.symmetric(vertical: 8.h),
                              leadingIcon: AppAssets.birthday_cake,
                              selectionType: SelectionTypeEnum.calendar,
                              onCalendarTypeChanged: authVm.onCalenderTypeChange,
                              onChange: authVm.onDobChange,
                            ).withVerticalPadding(8),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: 25.h),
                    GestureDetector(
                      onTap: authVm.onTermAccepted,
                      child: Row(
                        children: [
                          Selector<AuthenticationViewModel, 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.fSize, color: Colors.white) : null,
                              );
                            },
                          ),
                          SizedBox(width: 12.h),
                          Row(
                            children: [
                              Text(
                                LocaleKeys.iAcceptThe.tr(),
                                style: context.dynamicTextStyle(fontSize: 14.fSize, fontWeight: FontWeight.w500, color: Color(0xFF2E3039)),
                              ),
                              GestureDetector(
                                onTap: () {
                                  // Navigate to terms and conditions page
                                  Navigator.of(context).pushNamed('/terms');
                                },
                                child: Text(
                                  LocaleKeys.termsConditoins.tr(),
                                  style: context.dynamicTextStyle(
                                    fontSize: 14.fSize,
                                    fontWeight: FontWeight.w500,
                                    color: AppColors.primaryRedColor,
                                    decoration: TextDecoration.underline,
                                    decorationColor: AppColors.primaryRedBorderColor,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          // Expanded(
                          //   child: Text(
                          //     LocaleKeys.iAcceptTermsConditions.tr().split("the").first,
                          //     style: context.dynamicTextStyle(fontSize: 14.fSize, fontWeight: FontWeight.w500, color: Color(0xFF2E3039)),
                          //   ),
                          // ),
                        ],
                      ),
                    ),
                    SizedBox(height: 25.h),
                    CustomButton(
                      text: "Register",
                      icon: AppAssets.note_edit,
                      onPressed: () {
                        // Dismiss keyboard before proceeding
                        _nationalIdFocusNode.unfocus();
                        _dobFocusNode.unfocus();
                        FocusScope.of(context).unfocus();

                        if (ValidationUtils.isValidatedId(
                            nationalId: authVm.nationalIdController.text,
                            selectedCountry: authVm.selectedCountrySignup,
                            isTermsAccepted: authVm.isTermsAccepted,
                            dob: authVm.dobController.text,
                            onOkPress: () {
                              Navigator.of(context).pop();
                            })) {
                          showRegisterModel(context: context, authVM: authVm);
                        }
                      },
                    ),
                    SizedBox(height: 14),
                    Center(
                      child: RichText(
                        textAlign: TextAlign.center,
                        text: TextSpan(
                          style: context.dynamicTextStyle(
                            color: Colors.black,
                            fontSize: 16.fSize,
                            height: 26 / 16,
                            fontWeight: FontWeight.w500,
                          ),
                          children: <TextSpan>[
                            TextSpan(text: LocaleKeys.alreadyHaveAccount.tr(), style: context.dynamicTextStyle()),
                            TextSpan(text: "  "),
                            TextSpan(
                              text: LocaleKeys.loginNow.tr(),
                              style: context.dynamicTextStyle(
                                color: AppColors.primaryRedColor,
                                fontSize: 16.fSize,
                                height: 26 / 16,
                                fontWeight: FontWeight.w500,
                              ),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  Navigator.of(context).pop();
                                },
                            ),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: 30),
                  ],
                ),
              ),
            ),
          ),
        ));
  }

  void showRegisterModel({required BuildContext context, required AuthenticationViewModel authVM}) {
    AppState appState = getIt.get<AppState>();
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      isDismissible: false,
      useSafeArea: true,
      backgroundColor: Colors.transparent,
      builder: (bottomSheetContext) => Padding(
        padding: EdgeInsets.only(bottom: MediaQuery.of(bottomSheetContext).viewInsets.bottom),
        child: SingleChildScrollView(
          child: GenericBottomSheet(
            countryCode: authVM.selectedCountrySignup.countryCode,
            initialPhoneNumber: authVM.phoneNumberController.text,
            textController: authVM.phoneNumberController,
            isEnableCountryDropdown: false,
            onCountryChange: authVM.onCountryChange,
            onChange: authVM.onPhoneNumberChange,
            autoFocus: true,
            buttons: [
              Padding(
                padding: const EdgeInsets.only(bottom: 10),
                child: CustomButton(
                  text: LocaleKeys.sendOTPSMS.tr(),
                  onPressed: () async {
                    // Dismiss keyboard before validation
                    FocusScope.of(context).unfocus();

                    if (ValidationUtils.isValidatePhone(
                      phoneNumber: authVM.phoneNumberController.text,
                      onOkPress: () {
                        Navigator.of(context).pop();
                      },
                    )) {
                      appState.setSelectDeviceByImeiRespModelElement(null);
                      await authVM.onRegistrationStart(otpTypeEnum: OTPTypeEnum.sms);
                    }
                  },
                  backgroundColor: AppColors.primaryRedColor,
                  borderColor: AppColors.primaryRedBorderColor,
                  textColor: AppColors.whiteColor,
                  icon: AppAssets.message,
                ),
              ),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 8.h),
                    child: LocaleKeys.oR.tr().toText16(color: AppColors.textColor),
                  ),
                ],
              ),
              Padding(
                padding: EdgeInsets.only(bottom: 10.h, top: 10.h),
                child: CustomButton(
                  text: LocaleKeys.sendOTPWHATSAPP.tr(),
                  onPressed: () async {
                    FocusScope.of(context).unfocus();
                    if (ValidationUtils.isValidatePhone(
                      phoneNumber: authVM.phoneNumberController.text,
                      onOkPress: () {
                        Navigator.of(context).pop();
                      },
                    )) {
                      appState.setSelectDeviceByImeiRespModelElement(null);
                      await authVM.onRegistrationStart(otpTypeEnum: OTPTypeEnum.whatsapp);
                    }
                  },
                  backgroundColor: AppColors.whiteColor,
                  borderColor: AppColors.borderOnlyColor,
                  textColor: AppColors.textColor,
                  icon: AppAssets.whatsapp,
                  iconColor: null,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
