import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:proxibuy/data/models/categories/categories_model.dart';
import 'package:proxibuy/data/repositories/category_repository.dart';

part 'categories_children_state.dart';

class CategoriesChildrenCubit extends Cubit<CategoriesChildrenState> {
  CategoriesChildrenCubit() : super(CategoriesChildrenInitial());

  void updateCategories(List<CategoriesModel> newCategories) {
    emit(state.copyWith(categories: newCategories));
  }

  Future<void> getAllChildCategories(String id) async {
    if (state.isLoading || state.currentPage > state.totalPages) return;
    if (state.currentPage == 1) {
      emit(CategoriesChildrenLoading());
    } else {
      emit(state.copyWith(isLoading: true));
    }
    try {
      final response = await CategoryRepository.fetchAllChild(
          page: state.currentPage, id: id);
      emit(CategoriesChildrenLoaded(
        categories: List.from(state.categories)..addAll(response.data ?? []),
        isLoading: false,
        currentPage: state.currentPage + 1,
        totalPages: response.meta?.totalPages ?? 1,
      ));
    } catch (e) {
      emit(CategoriesChildrenError(e.toString()));
    }
  }

  Future resetPagination() async {
    emit(CategoriesChildrenInitial());
  }
}
