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

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

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

class ListTypeStateInit extends ListTypeState {
  ListTypeStateInit() : super(DateTime.now());
}

class ListTypeStateLoading extends ListTypeState {
  ListTypeStateLoading() : super(DateTime.now());
}

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

class ListTypeStateDone extends ListTypeState {
  final List<ListType> model;
  ListTypeStateDone({
    required this.model,
  }) : super(DateTime.now());
}

//notifier
class ListTypeNotifier extends StateNotifier<ListTypeState> {
  final Ref ref;
  ListTypeNotifier({
    required this.ref,
  }) : super(ListTypeStateInit());

  void getListType() async {
    try {
      state = ListTypeStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await TransaksiRepository(dio: dio).getListType();
      state = ListTypeStateDone(model: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = ListTypeStateError(message: e.message.toString());
      } else {
        state = ListTypeStateError(message: e.toString());
      }
    }
  }
}

//provider
final listTypeProvider = StateNotifierProvider<ListTypeNotifier, ListTypeState>(
  (ref) => ListTypeNotifier(ref: ref),
);
