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

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

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

class DeleteTransaksiStateInit extends DeleteTransaksiState {
  DeleteTransaksiStateInit() : super(DateTime.now());
}

class DeleteTransaksiStateLoading extends DeleteTransaksiState {
  DeleteTransaksiStateLoading() : super(DateTime.now());
}

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

class DeleteTransaksiStateDone extends DeleteTransaksiState {
  // final List<ListType> model;
  final String resp;
  DeleteTransaksiStateDone({
    required this.resp,
  }) : super(DateTime.now());
}

//notifier
class DeleteTransaksiNotifier extends StateNotifier<DeleteTransaksiState> {
  final Ref ref;
  DeleteTransaksiNotifier({
    required this.ref,
  }) : super(DeleteTransaksiStateInit());

  void deleteTransaksi(
    String id,
    String userid,
    String companyid,
    String tglAwal,
    String tglAkhir,
    String categoryid,
  ) async {
    try {
      state = DeleteTransaksiStateLoading();
      final dio = ref.read(dioProvider);
      final resp = await TransaksiRepository(dio: dio).deleteTransaksi(
        id,
        userid,
      );
      state = DeleteTransaksiStateDone(resp: resp);

      // search lagi buat get data
      ref.read(searchHistoryTransaksiProvider.notifier).searchHistoryTransaksi(
            companyid,
            tglAwal,
            tglAkhir,
            categoryid,
          );
    } catch (e) {
      if (e is BaseRepositoryException) {
        state = DeleteTransaksiStateError(message: e.message.toString());
      } else {
        state = DeleteTransaksiStateError(message: e.toString());
      }
    }
  }
}

//provider
final deleteTransaksiProvider =
    StateNotifierProvider<DeleteTransaksiNotifier, DeleteTransaksiState>(
  (ref) => DeleteTransaksiNotifier(ref: ref),
);
