import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../local_peference/local_preference.dart';
import '../../models/login_model.dart';
import '../../repositories/login_repository.dart';
part 'login_event.dart';
part 'login_state.dart';

class LoginBloc extends Bloc<LoginEvent, LoginState> {
  final LoginRepository _loginRepository;

  LoginBloc({LoginRepository? loginRepository})
      : _loginRepository = loginRepository ?? LoginRepository(),
        super(const LoginState()) {
    on<LoginSubmitted>(_onLoginSubmitted);
    on<LoginPasswordVisibilityToggled>(_onPasswordVisibilityToggled);
    on<LoginRememberMeToggled>(_onRememberMeToggled);
    on<LoginEmailErrorToggled>(_onEmailErrorToggled);
    on<LoginPasswordErrorToggled>(_onPasswordErrorToggled);
  }

  // ================= LOGIN SUBMITTED =================
  Future<void> _onLoginSubmitted(
      LoginSubmitted event,
      Emitter<LoginState> emit,
      ) async {
    emit(state.copyWith(status: LoginStatus.loading, errorMessage: null));

    try {
      final LoginModel loginData = await _loginRepository.login(
        emailAddress: event.emailAddress,
        password: event.password,
        rememberMe: event.rememberMe,
      );
      if (kDebugMode) {
        print('🔍 Login response accessToken: ${loginData.accessToken}');
        print('🔍 Login response refreshToken: ${loginData.refreshToken}');
      }
      // ── Save to local preference ──────────────────────────────────────
      await Future.wait([
        LocalPreference.setAccessToken(loginData.accessToken),
        LocalPreference.setRefreshToken(loginData.refreshToken),
        LocalPreference.setUserId(loginData.partner.id),
        LocalPreference.setLogin(true),
      ]);
      // ─────────────────────────────────────────────────────────────────

      emit(state.copyWith(
        status: LoginStatus.success,
        loginData: loginData,
      ));
    } catch (e) {
      emit(state.copyWith(
        status: LoginStatus.failure,
        errorMessage: e.toString().replaceAll('Exception: ', ''),
      ));
    }
  }

  // ================= PASSWORD VISIBILITY =================
  void _onPasswordVisibilityToggled(
      LoginPasswordVisibilityToggled event,
      Emitter<LoginState> emit,
      ) {
    emit(state.copyWith(isPasswordVisible: !state.isPasswordVisible));
  }

  // ================= REMEMBER ME =================
  void _onRememberMeToggled(
      LoginRememberMeToggled event,
      Emitter<LoginState> emit,
      ) {
    emit(state.copyWith(rememberMe: event.value));
  }

  void _onEmailErrorToggled(
      LoginEmailErrorToggled event,
      Emitter<LoginState> emit,
      ) {
    emit(state.copyWith(showEmailError: event.show));
  }

  void _onPasswordErrorToggled(
      LoginPasswordErrorToggled event,
      Emitter<LoginState> emit,
      ) {
    emit(state.copyWith(showPasswordError: event.show));
  }
}