// ignore: depend_on_referenced_packages;
import 'package:dartz/dartz.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:injectable/injectable.dart';

import '../../../common/utils/device_info_service.dart';
import '../../../common/utils/fcm_service.dart';
import '../../../domain/auth/auth.dart';

part 'login_form_event.dart';
part 'login_form_state.dart';
part 'login_form_bloc.freezed.dart';

@injectable
class LoginFormBloc extends Bloc<LoginFormEvent, LoginFormState> {
  final IAuthRepository _repository;
  final DeviceInfoService _deviceInfoService;
  final FcmService _fcmService;

  LoginFormBloc(this._repository, this._deviceInfoService, this._fcmService)
      : super(LoginFormState.initial()) {
    on<LoginFormEvent>(_onLoginFormEvent);
  }

  Future<void> _onLoginFormEvent(
    LoginFormEvent event,
    Emitter<LoginFormState> emit,
  ) {
    return event.map(
      emailChanged: (e) async {
        emit(state.copyWith(email: e.email, failureOrAuthOption: none()));
      },
      passwordChanged: (e) async {
        emit(state.copyWith(password: e.password, failureOrAuthOption: none()));
      },
      submitted: (e) async {
        Either<AuthFailure, Auth>? failureOrAuth;
        emit(state.copyWith(isSubmitting: true, failureOrAuthOption: none()));

        final emailValid = state.email.isNotEmpty;
        final passwordValid = state.password.isNotEmpty;

        if (emailValid && passwordValid) {
          // Ambil device info dan FCM token secara paralel
          final deviceInfo = await _deviceInfoService.getDeviceInfo();
          final fcmToken = await _fcmService.getToken();

          failureOrAuth = await _repository.login(
            email: state.email,
            password: state.password,
            deviceId: deviceInfo.deviceId,
            deviceName: deviceInfo.deviceName,
            deviceType: deviceInfo.deviceType,
            platform: deviceInfo.platform,
            osVersion: deviceInfo.osVersion,
            appVersion: deviceInfo.appVersion,
            fcmToken: fcmToken,
          );
          emit(
            state.copyWith(
              isSubmitting: false,
              failureOrAuthOption: optionOf(failureOrAuth),
            ),
          );
        }
        emit(state.copyWith(showErrorMessages: true, isSubmitting: false));
      },
    );
  }
}
