import 'package:cargocalculaterapp/core/local_source/local_source.dart';
import 'package:cargocalculaterapp/generated/l10n.dart';
import 'package:cargocalculaterapp/router/app_routes.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../../constants/constants.dart';
import '../../../../../injector_container.dart';
import '../../../../../router/name_routes.dart';
import '../../../data/model/login_request.dart';
import '../../../domain/usecases/login_usecase.dart';
import '../../pages/auth_confirm/argument/auth_confirm_argument.dart';

part 'auth_event.dart';

part 'auth_state.dart';

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  AuthBloc(this.loginUseCase)
    : super(
        const AuthState(
          passwordHidden: true,
          isLoading: false,
          isButtonEnabled: false,
        ),
      ) {
    on<PasswordVisibilityEvent>(_showHidePassword);
    on<OnInputEnterEvent>(_onInputEnter);
    on<SubmitEvent>(_onSubmit);
  }

  final LoginUseCase loginUseCase;

  void _showHidePassword(
    PasswordVisibilityEvent event,
    Emitter<AuthState> emit,
  ) {
    emit(state.copyWith(passwordHidden: !state.passwordHidden));
  }

  void _onInputEnter(OnInputEnterEvent event, Emitter<AuthState> emit) {
    emit(
      state.copyWith(
        isButtonEnabled:
            (isEmail(event.login) || isPhoneNumber(event.login)) &&
            event.password.isNotEmpty,
      ),
    );
  }

  Future<void> _onSubmit(SubmitEvent event, Emitter<AuthState> emit) async {
    emit(state.copyWith(isLoading: true));
    final response = await loginUseCase(
      LoginRequest(
        email: isEmail(event.login) ? event.login : "",
        phone: isPhoneNumber(event.login)
            ? event.login.replaceAll("+", "")
            : "",
        ucode: event.password,
      ),
    );
    response.fold(
      (l) {
        emit(state.copyWith(isLoading: false));
        showErrorSnackBar();
      },
      (r) {
        emit(state.copyWith(isLoading: false));
        sl<LocalSource>().setUCode(event.password);
        Navigator.pushNamed(
          rootNavigatorKey.currentContext!,
          Routes.authConfirm,
          arguments: AuthConfirmArgument(
            fullName: "",
            mail: isEmail(event.login) ? event.login : "",
            phoneNumber: isPhoneNumber(event.login) ? event.login : "",
            fromLoginPage: true,
            password: event.password,
          ),
        );
      },
    );
  }

  bool isEmail(String input) {
    return RegExConst.emailRegex.hasMatch(input);
  }

  bool isPhoneNumber(String input) {
    return RegExConst.phoneRegex.hasMatch(input);
  }

  void showErrorSnackBar() {
    final snackBar = SnackBar(
      backgroundColor: Colors.red,
      content: Row(
        children: [
          const Icon(Icons.error, color: Colors.white),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              AppLocalization.current.login_error,
              style: const TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
      behavior: SnackBarBehavior.floating,
      duration: const Duration(seconds: 3),
    );

    ScaffoldMessenger.of(
      rootNavigatorKey.currentContext!,
    ).showSnackBar(snackBar);
  }
}
