import 'package:baseproject/core/common/bloc/bloc_index.dart';
import 'package:baseproject/core/common/index.dart';
import 'package:baseproject/features/presentation/app/bloc/user_bloc.dart';
import 'package:baseproject/features/repositories/hra_repository.dart';
import 'package:baseproject/features/route/route_goto.dart';
import 'package:baseproject/features/usecases/user/user_use_cases.dart';
import 'package:flutter/material.dart';

class LoginViewModel {
  LoginViewModel({
    this.isLoading = false,
    this.loginResponse,
    this.captcha,
  });

  final bool isLoading;
  final LoginResponseDto? loginResponse;
  final DNTCaptchaApiResponse? captcha;

  LoginViewModel copyWith({
    bool? isLoading,
    String? errorMessage,
    LoginResponseDto? loginResponse,
    DNTCaptchaApiResponse? captcha,
  }) {
    return LoginViewModel(
      isLoading: isLoading ?? this.isLoading,
      loginResponse: loginResponse ?? this.loginResponse,
      captcha: captcha ?? this.captcha,
    );
  }
}

class LoginBloc extends BaseCubit<BaseStateBloc<LoginViewModel>> {
  LoginBloc(this._userUseCases) : super(InitState<LoginViewModel>(LoginViewModel())) {
    // loadCaptcha();
  }

  final UserUseCases _userUseCases;

  Future<void> loadCaptcha() async {
    final currentModel = state.model;

    final result = await _userUseCases.getCaptcha();

    result.fold(
      (error) {
        showErrorMessage(error);
      },
      (captcha) {
        emit(
          LoadedState<LoginViewModel>(
            currentModel.copyWith(
              isLoading: false,
              errorMessage: null,
              captcha: captcha,
            ),
          ),
        );
      },
    );
  }

  Future<void> login(LoginDto request, BuildContext context) async {
    final currentModel = state.model;

    emit(
      LoadingState<LoginViewModel>(
        currentModel.copyWith(isLoading: true, errorMessage: null),
      ),
    );

    final result = await _userUseCases.loginAccount(request);
    emit(
      LoadedState<LoginViewModel>(
        currentModel.copyWith(
          isLoading: false,
          errorMessage: null,
        ),
      ),
    );
    result.fold(
      (error) {
        showErrorMessage(error);
        // loadCaptcha();
      },
      (response) {
        BlocProvider.of<UserBloc>(context).updateUserInfo(response.userInfo ?? UserInfoDto());
        gotoHome(context);
      },
    );
  }
}
