
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/workin_area.dart';
import 'package:krow/core/data/enums/state_status.dart';
import 'package:krow/features/profile/working_area/data/working_area_repository.dart';
import 'package:rxdart/rxdart.dart';

part 'working_area_event.dart';
part 'working_area_state.dart';

class WorkingAreaBloc extends Bloc<WorkingAreaEvent, WorkingAreaState> {
  WorkingAreaBloc() : super(const WorkingAreaState()) {
    on<InitializeWorkingAreaEvent>(_onInitialize);
    on<CheckAreaEvent>(_onCheckArea);
    on<SubmitWorkingAreaEvent>(_onSubmit);
  }

  void _onInitialize(
      InitializeWorkingAreaEvent event, Emitter<WorkingAreaState> emit) async {
    emit(state.copyWith(status: StateStatus.loading));


    var staffWorkingAreasStream =
        getIt<WorkingAreaRepository>().getStaffWorkingAreas();
    var allWorkingAreasStream =
        getIt<WorkingAreaRepository>().getAllWorkingAreas();

    await for (var areas in CombineLatestStream.combine2(
      allWorkingAreasStream,
      staffWorkingAreasStream,
      (List<WorkingArea> allAreas, List<WorkingArea> staffAreas) {
        return allAreas.map((area) {
          var selected = staffAreas.any((assignedArea) => assignedArea.id == area.id);
          return AreaItemState(id: area.id, name: area.address, selected: selected);
        }).toList();
      },
    )) {
      emit(state.copyWith(status: StateStatus.idle, areas: areas));
    }
  }

  void _onCheckArea(CheckAreaEvent event, Emitter<WorkingAreaState> emit) {
    var areas = state.areas.map((e) {
      if (e.id == event.id) {
        return e.copyWith(selected: event.selected);
      }
      return e;
    }).toList();
    emit(state.copyWith(areas: areas));
  }

  void _onSubmit(
      SubmitWorkingAreaEvent event, Emitter<WorkingAreaState> emit) async {
    emit(state.copyWith(status: StateStatus.loading));
    var ids = state.areas
        .where((element) => element.selected)
        .map((e) => e.id)
        .toList();
    await getIt<WorkingAreaRepository>().saveWorkingArea(ids);
    emit(state.copyWith(status: StateStatus.success));
  }
}
