import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/blocs/auth/auth_bloc.dart';
import 'package:smart_hotel_app/blocs/auth/auth_event.dart';
import 'package:smart_hotel_app/blocs/auth/auth_state.dart';
import 'package:smart_hotel_app/utils/storage/storage_service.dart';
import 'package:smart_hotel_app/views/login/cubit/login_state.dart';

class LoginCubit extends Cubit<LoginState> {
  final AuthBloc authBloc;
  final StorageService storageService;

  LoginCubit({
    required this.authBloc,
    required this.storageService,
  }) : super(const LoginState()) {
    _listenAuthState();
  }

  void _listenAuthState() {
    authBloc.stream.listen((authState) {
      if (authState is AuthFailure) {
        emit(state.copyWith(isLoading: false, error: authState.error));
      } else if (authState is AuthLoading) {
        emit(state.copyWith(isLoading: true, error: null));
      } else if (authState is AuthSuccess) {
        emit(state.copyWith(isLoading: false, error: null));
      }
    });
  }

  void toggleRememberPassword(bool value) {
    emit(state.copyWith(rememberPassword: value));
  }

  void login({
    required String username,
    required String password,
    bool rememberPassword = false,
  }) {
    if (rememberPassword) {
      storageService.saveRememberCredentials(
        username: username,
        password: password,
      );
    } else {
      storageService.clearRememberCredentials();
    }

    authBloc.add(AuthLoginRequested(
      username: username,
      password: password,
    ));
  }

  Future<void> loadRememberCredentials() async {
    final credentials = await storageService.getRememberCredentials();
    if (credentials['username'] != null) {
      emit(state.copyWith(
        rememberPassword: true,
        savedUsername: credentials['username'],
        savedPassword: credentials['password'],
      ));
    }
  }

  void forgotPwd() {
    // TODO: 跳转到忘记密码页面
  }
}