import '../../model/list_category_model.dart';
import '../../repository/transaksi_repository.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../provider/dio_provider.dart';
import '../../repository/base_repository.dart';

abstract class ListCategoryState extends Equatable {
  final DateTime date;
  const ListCategoryState(this.date);
  @override
  List<Object?> get props => [date];
}

class ListCategoryStateInit extends ListCategoryState {
  ListCategoryStateInit() : super(DateTime.now());
}

class ListCategoryStateLoading extends ListCategoryState {
  ListCategoryStateLoading() : super(DateTime.now());
}

class ListCategoryStateError extends ListCategoryState {
  final String message;
  ListCategoryStateError({
    required this.message,
  }) : super(DateTime.now());
}

class ListCategoryStateDone extends ListCategoryState {
  final List<ListCategory> model;
  ListCategoryStateDone({
    required this.model,
  }) : super(DateTime.now());
}

//notifier
class ListCategoryNotifier extends StateNotifier<ListCategoryState> {
  final Ref ref;
  ListCategoryNotifier({
    required this.ref,
  }) : super(ListCategoryStateInit());

  void getListCategory() async {
    try {
      state = ListCategoryStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await TransaksiRepository(dio: dio).getListCategory();
      state = ListCategoryStateDone(model: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = ListCategoryStateError(message: e.message.toString());
      } else {
        state = ListCategoryStateError(message: e.toString());
      }
    }
  }
}

//provider
final listCategoryProvider = StateNotifierProvider<ListCategoryNotifier, ListCategoryState>(
  (ref) => ListCategoryNotifier(ref: ref),
);
