import 'dart:developer';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:krow/core/application/common/validators/email_validator.dart';
import 'package:krow/core/application/di/injectable.dart';
import 'package:krow/core/data/enums/state_status.dart';
import 'package:krow/core/data/models/client/client.dart';
import 'package:krow/features/profile/data/profile_repository.dart';

part 'personal_info_event.dart';
part 'personal_info_state.dart';

class PersonalInfoBloc extends Bloc<PersonalInfoEvent, PersonalInfoState> {
  PersonalInfoBloc() : super(const PersonalInfoState()) {
    on<InitializeProfileInfoEvent>(_onInitializeProfileInfoEvent);

    on<UpdateProfileImage>(_onUpdateProfileImage);

    on<UpdateFirstName>(_onUpdateFirstName);

    on<UpdateLastName>(_onUpdateLastName);

    on<UpdateEmail>(_onUpdateEmail);

    on<UpdatePhoneNumber>(_onUpdatePhoneNumber);

    on<SaveProfileChanges>(_onSaveProfileChanges);

    on<DeactivateProfile>(_onDeactivateProfile);
  }

  Future<void> _onInitializeProfileInfoEvent(
    InitializeProfileInfoEvent event,
    Emitter<PersonalInfoState> emit,
  ) async {
    emit(
      state.copyWith(
        status: StateStatus.idle,
      ),
    );

    await for (final currentProfileData
        in getIt<ClientProfileRepository>().getPersonalInfo()) {
      try {

        emit(
          state.copyWith(
            firstName: currentProfileData.firstName,
            lastName: currentProfileData.lastName,
            email: currentProfileData.authInfo?.email,
            profileImageUrl: currentProfileData.avatar,
            phoneNumber: currentProfileData.authInfo?.phone,
            isUpdateReceived: true,
            status: StateStatus.idle,
          ),
        );
      } catch (except) {
        log(except.toString());
      } finally {
        emit(state.copyWith(isUpdateReceived: false));
      }
    }

    if (state.status == StateStatus.loading) {
      emit(state.copyWith(status: StateStatus.idle));
    }
  }

  void _onUpdateProfileImage(
    UpdateProfileImage event,
    Emitter<PersonalInfoState> emit,
  ) {
    emit(state.copyWith(profileImagePath: event.imagePath));
  }

  void _onUpdateFirstName(
    UpdateFirstName event,
    Emitter<PersonalInfoState> emit,
  ) {
    emit(state.copyWith(firstName: event.firstName));
  }

  void _onUpdateLastName(
    UpdateLastName event,
    Emitter<PersonalInfoState> emit,
  ) {
    emit(state.copyWith(lastName: event.lastName));
  }

  void _onUpdateEmail(
    UpdateEmail event,
    Emitter<PersonalInfoState> emit,
  ) {
    final error = EmailValidator.validate(event.email);
    emit(
      state.copyWith(
        email: event.email,
        emailValidationError: error ?? '',
      ),
    );
  }

  void _onUpdatePhoneNumber(
    UpdatePhoneNumber event,
    Emitter<PersonalInfoState> emit,
  ) {
    emit(state.copyWith(phoneNumber: event.phoneNumber));
  }

  Future<void> _onSaveProfileChanges(
    SaveProfileChanges event,
    Emitter<PersonalInfoState> emit,
  ) async {
    if (!state.isValid) {
      emit(state.copyWith(status: StateStatus.error));
      return;
    }

    emit(state.copyWith(status: StateStatus.loading));

    ClientModel? response;
    try {
      response = await getIt<ClientProfileRepository>().updatePersonalInfo(
        firstName: state.firstName,
        lastName: state.lastName,
        phone: state.phoneNumber,
        avatarPath: state.profileImagePath,
      );
    } finally {
      emit(
        state.copyWith(
          status: response != null ? StateStatus.success : StateStatus.idle,
        ),
      );
    }
  }

  Future<void> _onDeactivateProfile(
    DeactivateProfile event,
    Emitter<PersonalInfoState> emit,
  ) async {
    emit(state.copyWith(status: StateStatus.loading));

    try {
      await getIt<ClientProfileRepository>().deactivateProfile();
    } finally {
      emit(state.copyWith(status: StateStatus.idle, deleted: true));
    }
  }
}
