
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow/core/application/di/injectable.dart';
import 'package:krow/core/data/models/staff/full_address_model.dart';
import 'package:krow/core/data/enums/state_status.dart';
import 'package:krow/features/profile/address/data/address_repository.dart';
import 'package:krow/features/profile/address/domain/google_places_service.dart';


part 'address_event.dart';
part 'address_state.dart';

class AddressBloc extends Bloc<AddressEvent, AddressState> {
  AddressBloc() : super(const AddressState()) {
    on<InitializeAddressEvent>(_onInitialize);
    on<SubmitAddressEvent>(_onSubmit);
    on<AddressQueryChangedEvent>(_onQueryChanged);
    on<AddressSelectEvent>(_onSelect);
  }

  void _onInitialize(
      InitializeAddressEvent event, Emitter<AddressState> emit) async {
    emit(state.copyWith(status: StateStatus.loading));
    await for (var address in getIt<AddressRepository>().getStaffAddress()) {
      emit(state.copyWith(
        fullAddress: address,
        status: StateStatus.idle,
      ));
    }
  }

  void _onQueryChanged(
      AddressQueryChangedEvent event, Emitter<AddressState> emit) async {
    try {
      final googlePlacesService = GooglePlacesService();
      final suggestions =
          await googlePlacesService.fetchSuggestions(event.query);
      emit(state.copyWith(suggestions: suggestions));
    } catch (e) {
      if (kDebugMode) print(e);
    }
  }

  void _onSelect(AddressSelectEvent event, Emitter<AddressState> emit) async {
    final googlePlacesService = GooglePlacesService();
    final fullAddress =
        await googlePlacesService.getPlaceDetails(event.place.placeId);
    FullAddress address = FullAddress.fromGoogle(fullAddress);
    emit(state.copyWith(suggestions: [], fullAddress: address));
  }

  void _onSubmit(SubmitAddressEvent event, Emitter<AddressState> emit) async {
    emit(state.copyWith(status: StateStatus.loading));
    try {
      await getIt<AddressRepository>().putAddress(state.fullAddress!);
      emit(state.copyWith(status: StateStatus.success));
    } catch (e) {
      emit(state.copyWith(status: StateStatus.error));
    }
  }
}
