import 'package:dio/dio.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:frontend_eccp_mobile/app/core/di/injection.dart';
import 'package:frontend_eccp_mobile/app/core/services/crashlytics_service.dart';
import 'package:frontend_eccp_mobile/app/core/utils/session_manager.dart';
import 'package:frontend_eccp_mobile/modules/auth/login/bloc/login_state.dart';
import 'package:frontend_eccp_mobile/modules/auth/login/data/model/login_request.dart';
import 'package:frontend_eccp_mobile/modules/auth/login/data/model/user_session.dart';
import 'package:frontend_eccp_mobile/modules/auth/login/data/repositories/login_repository.dart';
import 'package:injectable/injectable.dart';

@injectable
class LoginCubit extends Cubit<LoginState> {
  LoginCubit(this._repository) : super(LoginInitial());

  final LoginRepository _repository;

  Future<void> login({
    required String nrp,
    required String password,
  }) async {
    emit(LoginLoading());

    try {
      final response = await _repository.login(
        LoginRequest(
          nrp: nrp,
          password: password,
        ),
      );

      if (response.status != 'success') {
        emit(LoginFailure(response.message));
        return;
      }

      await CrashlyticsService.setUser(
        id: response.data.user.nrp,
        nrp: response.data.user.nrp,
        name: response.data.user.name,
      );

      await SessionManager.saveToken(response.data.accessToken);
      await SessionManager.saveRefreshToken(response.data.refreshToken);

      final userMap = {
        'name': response.data.user.name,
        'nrp': response.data.user.nrp,
      };

      await SessionManager.saveUser(userMap);

      final _ = getIt<UserSession>()
        ..token = response.data.accessToken
        ..user = userMap;

      emit(LoginSuccess());
    } on DioException catch (e) {
      final handled = e.requestOptions.extra['handledGlobally'] == true;
      if (handled) return;
      emit(LoginFailure(e.error?.toString()));
    } catch (e, s) {
      await CrashlyticsService.recordError(
        e,
        s,
        fatal: true,
        reason: 'Login Unknown Error',
      );

      emit(const LoginFailure('Terjadi kesalahan saat login'));
    }
  }
}
