import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../data/repository/repository.dart';
import '../../../../utils/local_storage.dart';
import '../../../../utils/validators.dart';
import '../models/request_user.dart';
import '../models/response_user.dart';

part 'login_state.dart';

class LoginCubit extends Cubit<LoginState> {
  LoginCubit() : super(LoginInitial());

  final formKey = GlobalKey<FormState>();
  final usernameCtl = TextEditingController();
  final passwordCtl = TextEditingController();
  final usernameFocus = FocusNode();
  final passwordFocus = FocusNode();
  final _repository = Repository();

  var isRemember = ValueNotifier(true);

  Future<void> loginWithCredential() async {
    // if (!formKey.currentState!.validate()) {
    //   return;
    // }

    emit(LoginLoading());
    var userLoginRequest = RequestUser()
      ..username = usernameCtl.text
      ..password = passwordCtl.text;
    await _repository.login(
      (data) {
        handleLoginLogic(
          responseUser: data,
          username: usernameCtl.text,
        );
      },
      (error) {
        emit(LoginFailure('Tên đăng nhập hoặc mật khẩu không đúng'));
      },
      requestUser: userLoginRequest,
    );
  }

  Future<void> handleLoginLogic({
    required ResponseUser responseUser,
    required String username,
  }) async {
    try {
      LocalStorage.saveUserInfo(responseUser, username);
    } catch (_) {}
    emit(
      LoginSuccess(
        routeName: '',
      ),
    );
  }

  String? validateEmail(String value) {
    if (!Validators.stringNotNullOrEmpty(value)) {
      return 'Nhập email';
    }
    if (!Validators.isValidEmail(value)) {
      return 'Nhập email';
    }
    return null;
  }

  String? validatePassword(String value) {
    if (!Validators.stringNotNullOrEmpty(value)) {
      return 'Nhập mật khẩu';
    }
    return null;
  }

  void rememberMe(bool isRememberLogin) {
    isRemember.value = isRememberLogin;
  }

  void dispose() {
    usernameCtl.dispose();
    passwordCtl.dispose();
    usernameFocus.dispose();
    passwordFocus.dispose();
  }
}
