import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:tanami_app/Api_Helper/base_manager.dart';
import 'package:tanami_app/Globalconst.dart';
import 'package:tanami_app/features/login/Repository/LoginAPI.dart';

import '../../../../core/utils/secure/secure_storage_service.dart';
import 'login_event.dart';
import 'login_state.dart';

class LoginBloc extends Bloc<LoginEvent, LoginState> {
  final SharedPreferenceLocalData secureStorageService;
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final TextEditingController countrySelectionTextField =
      TextEditingController();
  final TextEditingController phoneNumberTextField = TextEditingController();
  final TextEditingController passwordTextField = TextEditingController();
  String countryId = "";
  String isdcode = "";
  GlobalKey<FormState> getFormKey() {
    return formKey;
  }

  LoginBloc({required this.secureStorageService}) : super(LoginInitial()) {
    phoneNumberTextField.addListener(_onFormFieldChanged);
    passwordTextField.addListener(_onFormFieldChanged);
    countrySelectionTextField.addListener(_onFormFieldChanged);
    on<LoginFormChanged>(_onLoginFormChanged);
    on<LoginSubmitted>((event, emit) async {
      if (!formKey.currentState!.validate()) {
        emit(LoginLoading());
        emit(LoginFailure(Globalconst.languageSelected == "en"
            ? "Login failed. Please check your credentials."
            : "فشل تسجيل الدخول. يرجى التحقق من بيانات الاعتماد الخاصة بك."));
        return;
      }
      emit(LoginLoading());
      try {
        Map<String, dynamic> logindata = {
          "ISDcode": event.isdCode,
          "mobileNumber": event.phoneNumber,
          "password": event.password
        };
        ResponseData response = await LoginAPI().LoginRequest(logindata);
        if (response.status == ResponseStatus.SUCCESS) {
          await secureStorageService.write(
              'first_name', response.data['data']['firstName']);
          Globalconst.firstName = response.data['data']['firstName'];
          Globalconst.lastName = response.data['data']['lastName'];
          await secureStorageService.write(
              'temp_token', response.data['data']['code']);
          if (response.data["data"]["isMasterPin"] == false) {
            await secureStorageService.write(
                'temp_token', response.data['data']['code']);
            emit(LoginMasterPinPending());
          } else {
            emit(LoginSuccess());
          }
        } else if (response.status == ResponseStatus.PRIVATE) {
          emit(LoginFailure(response.message.toString()));
        } else {
          emit(LoginFailure(response.message.toString()));
        }
      } catch (e) {
        emit(LoginFailure(e.toString()));
      }
    });
  }
  void _onFormFieldChanged() {
    add(LoginFormChanged(
      phoneNumberTextField.text,
      passwordTextField.text,
      countrySelectionTextField.text,
    ));
  }

  void _onLoginFormChanged(LoginFormChanged event, Emitter<LoginState> emit) {
    final areFieldsFilled = event.phoneNumber.isNotEmpty &&
        event.password.isNotEmpty &&
        event.country.isNotEmpty;
    emit(LoginFieldsState(areFieldsFilled));
  }

  // Method to reset text fields
  void resetFields() {
    phoneNumberTextField.clear();
    passwordTextField.clear();
    countrySelectionTextField.clear();
  }

  @override
  Future<void> close() {
    phoneNumberTextField.dispose();
    passwordTextField.dispose();
    countrySelectionTextField.dispose();
    return super.close();
  }
}
