import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';

import '../../../../Api_Helper/base_manager.dart';
import '../../../../core/utils/secure/secure_storage_service.dart';
import '../../../otpVerification/domain/Repository/otp_api.dart';
import 'register_event.dart';
import 'register_state.dart';

class RegisterBloc extends Bloc<RegisterEvent, RegisterState> {
  final SecureStorageService secureStorageService;
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final TextEditingController countrySelectionTextField =
      TextEditingController();
  String isdcode = "";
  String countryId = "";
  final TextEditingController phoneNumberTextField = TextEditingController();

  GlobalKey<FormState> getFormKey() {
    return formKey;
  }

  RegisterBloc({required this.secureStorageService})
      : super(RegisterInitial()) {
    phoneNumberTextField.addListener(_onFormFieldChanged);
    countrySelectionTextField.addListener(_onFormFieldChanged);
    on<RegisterFormChanged>(_onLoginFormChanged);
    on<RegisterSubmitted>((event, emit) async {
      if (!formKey.currentState!.validate()) {
        return;
      }
      emit(RegisterLoading());
      try {
        Map<String, dynamic> requestdata = {
          "ISDcode": event.isdcode,
          "mobileNumber": event.phoneNumber
        };
        ResponseData response = await OTPAPI().requestOTP(requestdata);
        if (response.status == ResponseStatus.SUCCESS) {
          var data = response.data;
          String token = data["data"];
          await secureStorageService.write('temp_token', token);
          emit(RegisterSuccess(token)); //emit(OTPLoaded());
        } else {
          emit(RegisterFailure(response.message));
        }
      } catch (e) {
        emit(RegisterFailure(e.toString()));
      }
    });

    on<Resendotp>((event, emit) async {
      emit(RegisterLoading());
      try {
        Map<String, dynamic> requestdata = {
          "code": await secureStorageService.read('temp_token'),
        };
        ResponseData response = await OTPAPI().resendOTPRequest(requestdata);
        if (response.status == ResponseStatus.SUCCESS) {
          emit(RegisterSuccess(event.token)); //emit(OTPLoaded());
        } else {
          emit(RegisterFailure(response.message.toString()));
          //emit(OTPFailed("Oops something went wrong"));
        }
      } catch (e) {
        emit(RegisterFailure(e.toString()));
      }
    });
  }
  void _onFormFieldChanged() {
    add(RegisterFormChanged(
      phoneNumberTextField.text,
      countrySelectionTextField.text,
    ));
  }

  void _onLoginFormChanged(
      RegisterFormChanged event, Emitter<RegisterState> emit) {
    final areFieldsFilled =
        event.phoneNumber.isNotEmpty && event.country.isNotEmpty;
    emit(RegisterFieldsState(areFieldsFilled));
  }

  @override
  Future<void> close() {
    phoneNumberTextField.dispose();

    countrySelectionTextField.dispose();
    return super.close();
  }
}
