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/enums.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/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/e_referral/e_referral_form_manager.dart';
import 'package:hmg_patient_app_new/theme/colors.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/loader/bottomsheet_loader.dart';
import 'package:provider/provider.dart';
import 'package:hmg_patient_app_new/core/common_models/generic_api_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/req_models/send_activation_code_ereferral_req_model.dart';

class OTPService {
  static void openOTPScreen({
    required BuildContext context,
    required ReferralFormManager formManager,
    required Function onSuccess,
  }) {
    _showOTPVerificationSheet(context: context, formManager: formManager, onSuccess: onSuccess);
  }

  static void _showOTPVerificationSheet({
    required BuildContext context,
    required ReferralFormManager formManager,
    required Function onSuccess,
  }) {
    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(
              isEnableCountryDropdown: true,
              textController: TextEditingController(),
              onChange: (value) {
                formManager.updateRequesterPhone(value ?? '');
              },
              onCountryChange: (value) {
                formManager.updateCountryEnum(value);
              },
              autoFocus: true,
              buttons: [
                Padding(
                  padding: const EdgeInsets.only(bottom: 10),
                  child: CustomButton(
                    text: LocaleKeys.sendOTPSMS.tr(),
                    onPressed: () async {
                      if (ValidationUtils.isValidatePhone(
                        phoneNumber: formManager.formData.requesterPhone,
                        onOkPress: () {
                          Navigator.pop(context);
                        },
                      )) {
                        Navigator.pop(context);
                        final hmgServicesViewModel = context.read<HmgServicesViewModel>();

                        // Start listening for SMS before sending OTP
                        _startSmsListener(
                          context: context,
                          hmgServicesViewModel: hmgServicesViewModel,
                          formManager: formManager,
                          onSuccess: onSuccess,
                        );
                      }
                    },
                    backgroundColor: AppColors.primaryRedColor,
                    borderColor: AppColors.primaryRedBorderColor,
                    textColor: Colors.white,
                    iconColor: Colors.white,
                    icon: AppAssets.message,
                  ),
                ),
              ],
            ),
          )),
    );
  }

  static void _startSmsListener({
    required BuildContext context,
    required HmgServicesViewModel hmgServicesViewModel,
    required ReferralFormManager formManager,
    required Function onSuccess,
  }) async {
    LoaderBottomSheet.showLoader();

    // Send OTP after starting listener
    hmgServicesViewModel.eReferralSendActivationCode(
      requestModel: SendActivationCodeForEReferralRequestModel(
        patientMobileNumber: int.parse(formManager.formData.requesterPhone),
        zipCode: formManager.formData.countryEnum.countryCode,
        patientOutSA: formManager.formData.countryEnum.countryCode == '966' ? 0 : 1,
      ),
      onSuccess: (GenericApiModel response) {
        LoaderBottomSheet.hideLoader();
        hmgServicesViewModel.navigateToOTPScreen(
            otpTypeEnum: OTPTypeEnum.sms,
            phoneNumber: formManager.formData.requesterPhone,
            loginToken: response.data,
            onSuccess: () {
              Navigator.pop(context);
              onSuccess();
            });
      },
      onError: (String errorMessage) {
        LoaderBottomSheet.hideLoader();
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage)));
      },
    );
  }
}
