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 '../../../../../core/error/failure.dart';
import '../../../../../core/functions/base_finctions.dart';
import '../../../../../injector_container.dart';
import '../../../../../router/name_routes.dart';
import '../../../data/model/sign_up_request.dart';
import '../../../domain/usecases/sign_up_usecase.dart';
import '../../pages/auth_confirm/argument/auth_confirm_argument.dart';

part 'sign_up_event.dart';

part 'sign_up_state.dart';

class SignUpBloc extends Bloc<SignUpEvent, SignUpState> {
  SignUpBloc(this.signUpUseCase)
    : super(
        const SignUpState(
          isLoading: false,
          isButtonEnabled: false,
          passwordHidden: true,
        ),
      ) {
    on<PasswordVisibilityEvent>(_passwordVisibility);
    on<OnInputEnterEvent>(_onDataEnter);
    on<SubmitEvent>(_signUp);
  }

  final SignUpUseCase signUpUseCase;

  void _passwordVisibility(
    PasswordVisibilityEvent event,
    Emitter<SignUpState> emit,
  ) {
    emit(state.copyWith(isButtonEnabled: !state.isButtonEnabled));
  }

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

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

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

  Future<void> _signUp(SubmitEvent event, Emitter<SignUpState> emit) async {
    emit(state.copyWith(isLoading: true));
    final response = await signUpUseCase(
      SignUpRequest(
        fullname: event.fullName,
        email: isEmail(event.login) ? event.login : "",
        phoneNumber: isPhoneNumber(event.login)
            ? event.login.replaceAll("+", "")
            : "",
      ),
    );
    response.fold(
      (l) {
        emit(state.copyWith(isLoading: false));
        if (l is ServerFailure) {
          Functions.showErrorSnackBar(AppLocalization.current.phone_registered);
        }
      },
      (r) {
        sl<LocalSource>().setAccessToken(r.token ?? "");
        emit(state.copyWith(isLoading: false));
        Navigator.pushNamed(
          rootNavigatorKey.currentContext!,
          Routes.authConfirm,
          arguments: AuthConfirmArgument(
            fullName: event.fullName,
            mail: isEmail(event.login) ? event.login : "",
            phoneNumber: isPhoneNumber(event.login) ? event.login : "",
            fromLoginPage: false,
          ),
        );
      },
    );
  }
}
