// ignore_for_file: depend_on_referenced_packages

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:bloc/bloc.dart';
import 'package:gshop/domain/di/dependency_manager.dart';
import 'package:gshop/infrastructure/model/model/filter_model.dart';
import 'package:gshop/infrastructure/model/response/filter_response.dart';
import 'package:gshop/infrastructure/service/services.dart';

part 'filter_event.dart';

part 'filter_state.dart';

part 'filter_bloc.freezed.dart';

class FilterBloc extends Bloc<FilterEvent, FilterState> {
  FilterBloc() : super(const FilterState()) {
    on<ClearFilter>(clearFilter);

    on<SelectType>(selectType);

    on<SetRangePrice>(setRangePrice);

    on<SetExtras>(setExtras);

    on<SetCategory>(setCategory);

    on<SetBrands>(setBrands);

    on<FetchExtras>(fetchExtras);
  }

  clearFilter(event, emit) {
    emit(state.copyWith(
        categories: [],
        brands: [],
        extras: [],
        selectType: LayoutType.twoH,
        rangeValues: null));
  }

  selectType(event, emit) {
    emit(state.copyWith(selectType: event.selectType));
  }

  setRangePrice(event, emit) {
    emit(state.copyWith(rangeValues: event.price));
  }

  setExtras(event, emit) {
    List<int> list = List.from(state.extras ?? []);
    if (list.contains(event.id)) {
      list.remove(event.id);
    } else {
      list.add(event.id);
    }
    emit(state.copyWith(extras: list));
  }

  setCategory(event, emit) {
    List<int> list = List.from(state.categories ?? []);
    if (list.contains(event.id)) {
      list.remove(event.id);
    } else {
      list.add(event.id);
    }
    emit(state.copyWith(categories: list));
  }

  setBrands(event, emit) {
    if (event.id == -1) {
      return;
    }
    List<int> list = List.from(state.brands ?? []);
    if (list.contains(event.id)) {
      list.remove(event.id);
    } else {
      list.add(event.id);
    }
    emit(state.copyWith(brands: list));
  }

  fetchExtras(event, emit) async {
    if (event.isPrice) {
      emit(state.copyWith(rangeValues: null));
    }
    if (event.type != null) {
      emit(state.copyWith(type: event.type ?? "category"));
    }

    emit(state.copyWith(isLoading: true));
    final res = await productsRepository.fetchFilter(
        filter: FilterModel(
            type: state.type,
            extrasId: state.extras,
            categoryId: state.categories,
            parentId: event.categoryId,
            brandId: state.brands,
            priceFrom: state.rangeValues?.start,
            priceTo: state.rangeValues?.end));
    res.fold((l) {
      if (event.isPrice) {
        emit(
          state.copyWith(
              isLoading: false,
              filter: l,
              filterPrices: l.price,
              rangeValues: RangeValues(
                (l.price?.min ?? 0).toDouble(),
                (l.price?.max ?? 0).toDouble(),
              ),
              prices: List.generate(
                  (30).round(), (index) => (Random().nextInt(8) + 1))),
        );
        return;
      }
      emit(
        state.copyWith(isLoading: false, filter: l),
      );
    }, (r) {
      emit(state.copyWith(isLoading: false));
      AppHelpers.errorSnackBar(context: event.context, message: r);
    });
  }
}
