import 'package:equatable/equatable.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../model/history_transaksi_model.dart';
import '../../repository/transaksi_repository.dart';
import '../../provider/dio_provider.dart';
import '../../repository/base_repository.dart';

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

class SearchHistoryTransaksiStateInit extends SearchHistoryTransaksiState {
  SearchHistoryTransaksiStateInit() : super(DateTime.now());
}

class SearchHistoryTransaksiStateLoading extends SearchHistoryTransaksiState {
  SearchHistoryTransaksiStateLoading() : super(DateTime.now());
}

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

class SearchHistoryTransaksiStateDone extends SearchHistoryTransaksiState {
  final List<HistoryTransaksiModel> model;
  SearchHistoryTransaksiStateDone({
    required this.model,
  }) : super(DateTime.now());
}

//notifier
class SearchHistoryTransaksiNotifier
    extends StateNotifier<SearchHistoryTransaksiState> {
  final Ref ref;
  SearchHistoryTransaksiNotifier({
    required this.ref,
  }) : super(SearchHistoryTransaksiStateInit());

  void searchHistoryTransaksi(
    String companyid,
    String tglAwal,
    String tglAkhir,
     String categoryid,
  ) async {
    try {
      state = SearchHistoryTransaksiStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await TransaksiRepository(dio: dio).getListHistoryTransaksi(
       companyid,
       tglAwal,
       tglAkhir,
       categoryid,
      );
      state = SearchHistoryTransaksiStateDone(model: resp);
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = SearchHistoryTransaksiStateError(message: e.message.toString());
      } else {
        state = SearchHistoryTransaksiStateError(message: e.toString());
      }
    }
  }
}

//provider
final searchHistoryTransaksiProvider = StateNotifierProvider<
    SearchHistoryTransaksiNotifier, SearchHistoryTransaksiState>(
  (ref) => SearchHistoryTransaksiNotifier(ref: ref),
);
