import 'package:cargocalculaterapp/core/local_source/local_source.dart';
import 'package:cargocalculaterapp/core/usecase/usecase.dart';
import 'package:cargocalculaterapp/router/app_routes.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../constants/constants.dart';
import '../../../../injector_container.dart';
import '../../../../router/name_routes.dart';
import '../../data/models/profile_response.dart';
import '../../data/models/profile_update_request.dart';
import '../../domain/usecase/delete_profile_usecase.dart';
import '../../domain/usecase/profile_update_usecase.dart';
import '../../domain/usecase/profile_usecase.dart';

part 'profile_event.dart';

part 'profile_state.dart';

class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
  ProfileBloc(
    this.profileUseCase,
    this.profileUpdateUseCase,
    this.deleteProfileUseCase,
  ) : super(const ProfileState(readOnly: true, isLoading: false)) {
    on<GetProfileDataEvent>(_getProfileData);
    on<EditProfileEvent>(_editProfile);
    on<UpdateProfileEvent>(_updateUserInfo);
    on<DeleteProfileEvent>(_deleteProfile);
  }

  final ProfileUseCase profileUseCase;
  final ProfileUpdateUseCase profileUpdateUseCase;
  final DeleteProfileUseCase deleteProfileUseCase;

  Future<void> _getProfileData(
    GetProfileDataEvent event,
    Emitter<ProfileState> emit,
  ) async {
    emit(state.copyWith(isLoading: true));
    final cacheResponse = await profileUseCase(true);
    cacheResponse.fold((l) {}, (r) {
      emit(state.copyWith(isLoading: false, profileData: r));
    });
    final response = await profileUseCase(false);
    response.fold(
      (l) {
        emit(state.copyWith(isLoading: false));
      },
      (r) {
        sl<LocalSource>().setUCode(r.ucode ?? "");
        emit(state.copyWith(isLoading: false, profileData: r));
      },
    );
  }

  void _editProfile(EditProfileEvent event, Emitter<ProfileState> emit) {
    emit(state.copyWith(readOnly: false));
  }

  Future<void> _updateUserInfo(
    UpdateProfileEvent event,
    Emitter<ProfileState> emit,
  ) async {
    bool hasError = false;
    if (event.fullName.isEmpty) {
      hasError = true;
    } else if ((event.phone.isNotEmpty) &&
        !RegExConst.phoneRegex.hasMatch(event.phone)) {
      hasError = true;
    } else if ((event.email.isNotEmpty) &&
        !RegExConst.emailRegex.hasMatch(event.email)) {
      hasError = true;
    }
    if (hasError) {
      emit(state.copyWith(hasError: true));
      return;
    } else {
      emit(state.copyWith(hasError: false, isLoading: true));
    }
    final response = await profileUpdateUseCase(
      ProfileUpdateRequest(
        email: event.email,
        phoneNumber: event.phone.replaceAll("+", ""),
        fullname: event.fullName,
      ),
    );
    response.fold(
      (l) {
        emit(state.copyWith(isLoading: false));
      },
      (r) {
        emit(state.copyWith(isLoading: false, readOnly: true));
      },
    );
  }

  Future<void> _deleteProfile(
    DeleteProfileEvent event,
    Emitter<ProfileState> emit,
  ) async {
    final response = await deleteProfileUseCase(const NoParams());
    await response.fold((l) {}, (r) async {
      final language = sl<LocalSource>().getLocale();
      await sl<LocalSource>().clear().then((value) {
        sl<LocalSource>().setLocale(language);
        sl<LocalSource>().setIsFirstEnter(false);
        if (rootNavigatorKey.currentContext?.mounted ?? false) {
          Navigator.pushNamedAndRemoveUntil(
            rootNavigatorKey.currentContext!,
            Routes.auth,
            (route) => false,
          );
        }
      });
    });
  }
}
