import 'dart:async';

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;
  late final StreamSubscription _authSubscription;

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

  void _listenAuthState() {
    _authSubscription = authBloc.stream.listen(
      _onAuthStateChanged,
      onError: _onAuthError,
    );
  }

  void _onAuthStateChanged(AuthState authState) {
    // 检查 Cubit 是否已关闭
    if (isClosed) return;

    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 _onAuthError(error) {
    if (isClosed) return;
    emit(state.copyWith(isLoading: false, error: error.toString()));
  }

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

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

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

  Future<void> loadRememberCredentials() async {
    if (isClosed) return;

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

  void forgotPwd() {

  }

  @override
  Future<void> close() {
    _authSubscription.cancel();
    return super.close();
  }

}