import 'package:dartz/dartz.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:injectable/injectable.dart';

import '../../../domain/analytic/analytic.dart';
import '../../../domain/analytic/repositories/i_analytic_repository.dart';

part 'profit_sharing_detail_loader_event.dart';
part 'profit_sharing_detail_loader_state.dart';
part 'profit_sharing_detail_loader_bloc.freezed.dart';

@injectable
class ProfitSharingDetailLoaderBloc
    extends
        Bloc<ProfitSharingDetailLoaderEvent, ProfitSharingDetailLoaderState> {
  final IAnalyticRepository _repository;

  ProfitSharingDetailLoaderBloc(this._repository)
    : super(ProfitSharingDetailLoaderState.initial()) {
    on<ProfitSharingDetailLoaderEvent>(_onProfitSharingDetailLoaderEvent);
  }

  Future<void> _onProfitSharingDetailLoaderEvent(
    ProfitSharingDetailLoaderEvent event,
    Emitter<ProfitSharingDetailLoaderState> emit,
  ) {
    return event.map(
      expandedCategoryChanged: (e) async {
        final isSame = state.expandedCategoryId == e.categoryId;
        emit(state.copyWith(expandedCategoryId: isSame ? '' : e.categoryId));
      },
      fetched: (e) async {
        emit(
          state.copyWith(
            isFetching: true,
            failureOption: none(),
            parentCategoryId: e.parentCategoryId,
            dateFrom: e.dateFrom,
            dateTo: e.dateTo,
          ),
        );

        final result = await _repository.getProfitSharingDetail(
          parentCategoryId: e.parentCategoryId,
          dateFrom: e.dateFrom,
          dateTo: e.dateTo,
        );

        final newState = result.fold(
          (f) => state.copyWith(failureOption: optionOf(f)),
          (detail) => state.copyWith(
            detail: detail,
            // Sub kategori pertama langsung terbuka supaya produknya kelihatan.
            expandedCategoryId: detail.categories.isEmpty
                ? ''
                : detail.categories.first.categoryId,
          ),
        );

        emit(newState.copyWith(isFetching: false));
      },
    );
  }
}
