import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:farm_tpf/utils/helpers.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import '../../../../data/api/app_exception.dart';
import '../../../../data/repository/repository.dart';
import '../../../../models/item_dropdown.dart';
import '../../../../utils/const_common.dart';
import '../models/stamp.dart';
import '../models/stamp_filter_request.dart';

part 'stamp_event.dart';
part 'stamp_state.dart';

class StampBloc extends Bloc<StampEvent, StampState> {
  final Repository repository;
  int pageSize = 20;
  StampBloc(this.repository) : super(StampInitial());
  final searchCtl = TextEditingController();
  var status = ValueNotifier(
    StampStatus.values
        .map(
          (e) => ItemDropDown(key: describeEnum(e), value: Helpers.getStampStatus(describeEnum(e))),
        )
        .toList(),
  );

  var selectedStatus = ValueNotifier(
    StampStatus.values
        .map(
          (e) => ItemDropDown(key: describeEnum(e), value: Helpers.getStampStatus(describeEnum(e))),
        )
        .toList(),
  );
  var sort = ValueNotifier(describeEnum(SortType.asc));

  @override
  Stream<StampState> mapEventToState(
    StampEvent event,
  ) async* {
    if (event is DataFetched && !(state is StampSuccess && ((state as StampSuccess).hasReachedMax ?? false))) {
      try {
        if (state is StampInitial) {
          yield (StampLoading());
          final response = await getListStamp(0);
          yield StampSuccess(
            items: response,
            page: 0,
            hasReachedMax: response.length < pageSize ? true : false,
          );
        }
        if (state is StampSuccess) {
          final currentState = state as StampSuccess;
          if (currentState.hasReachedMax ?? false) {
            return;
          }
          int page = (currentState.page ?? 0) + 1;
          final response = await getListStamp(page);
          yield response.isEmpty
              ? currentState.copyWith(hasReachedMax: true)
              : StampSuccess(
                  items: (currentState.items ?? []) + response,
                  page: (currentState.page ?? 0) + 1,
                  hasReachedMax: false,
                );
        }
      } catch (e) {
        var errorString = AppException.handleError(e);
        yield (StampFailure(errorString: errorString));
      }
    }
    if (event is OnRefresh) {
      try {
        yield (StampLoading());
        final response = await getListStamp(0);
        yield StampSuccess(
          items: response,
          page: 0,
          hasReachedMax: response.length < pageSize ? true : false,
        );
      } catch (e) {
        yield (StampFailure(errorString: AppException.handleError(e)));
      }
    } else if (event is OnSearch) {
      try {
        yield (StampLoading());
        final response = await getListStamp(0);
        yield StampSuccess(items: response, page: 0, hasReachedMax: response.length < pageSize ? true : false);
      } catch (e) {
        yield (StampFailure(errorString: AppException.handleError(e)));
      }
    }
  }

  Future<List<Stamp>> getListStamp(int page) async {
    var filter = StampFilterRequest()
      ..sort = sort.value
      ..description = searchCtl.text
      ..status = selectedStatus.value.map((e) => e.key ?? '').toList();
    return await repository.stamps(page: 0, filter: filter);
  }
}
