import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:tanami_app/Api_Helper/base_manager.dart';
import 'package:tanami_app/features/register/Repository/RegisterApi.dart';

import '../../../../core/utils/secure/secure_storage_service.dart';
import 'register_user_event.dart';
import 'register_user_state.dart';

class RegisterUserBloc extends Bloc<RegisterUserEvent, RegisterUserState> {
  final SecureStorageService secureStorageService;
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final TextEditingController firstNameTextField = TextEditingController();
  final TextEditingController lastNameTextField = TextEditingController();
  final TextEditingController emailTextField = TextEditingController();
  final TextEditingController passwordTextField = TextEditingController();
  final TextEditingController repeatPasswordTextField = TextEditingController();

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

  RegisterUserBloc({required this.secureStorageService})
      : super(RegisterUserInitial()) {
    firstNameTextField.addListener(_onFormFieldChanged);
    passwordTextField.addListener(_onFormFieldChanged);
    lastNameTextField.addListener(_onFormFieldChanged);
    emailTextField.addListener(_onFormFieldChanged);
    repeatPasswordTextField.addListener(_onFormFieldChanged);

    on<RegisterFormChanged>(_onLoginFormChanged);
    on<RegisterUserSubmitted>((event, emit) async {
      if (!formKey.currentState!.validate()) {
        return;
      }
      emit(RegisterUserLoading());
      try {
        Map<String, dynamic> registerdata = {
          "code": event.token,
          "firstName": event.firstName,
          "lastName": event.lastName,
          "emailAddress": event.email,
          "password": event.password,
          "confirmPassword": event.password,
        };
        ResponseData response =
            await RegisterAPIService().RegisterRequest(registerdata);
        if (response.status == ResponseStatus.SUCCESS) {
          var data = response.data["data"];
          secureStorageService.write("temp_token", data["token"].toString());
          emit(RegisterUserSuccess());
        } else {
          emit(RegisterUserFailure(response.message));
        }
      } catch (e) {
        emit(RegisterUserFailure(e.toString()));
      }
    });
  }
  void _onFormFieldChanged() {
    add(RegisterFormChanged(
      firstNameTextField.text,
      lastNameTextField.text,
      emailTextField.text,
      passwordTextField.text,
      repeatPasswordTextField.text,
    ));
  }

  void _onLoginFormChanged(
      RegisterFormChanged event, Emitter<RegisterUserState> emit) {
    final areFieldsFilled = event.firstName.isNotEmpty &&
        event.lastName.isNotEmpty &&
        event.email.isNotEmpty &&
        event.password.isNotEmpty &&
        event.confirmPassword.isNotEmpty;
    emit(RegisterUserFieldsState(areFieldsFilled));
  }

  @override
  Future<void> close() {
    firstNameTextField.dispose();
    passwordTextField.dispose();
    lastNameTextField.dispose();
    emailTextField.dispose();
    repeatPasswordTextField.dispose();
    return super.close();
  }
}
