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 ConfirmTransaksiState extends Equatable {
  final DateTime date;
  const ConfirmTransaksiState(this.date);
  @override
  List<Object?> get props => [date];
}

class ConfirmTransaksiStateInit extends ConfirmTransaksiState {
  ConfirmTransaksiStateInit() : super(DateTime.now());
}

class ConfirmTransaksiStateLoading extends ConfirmTransaksiState {
  ConfirmTransaksiStateLoading() : super(DateTime.now());
}

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

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

//notifier
class ConfirmTransaksiNotifier extends StateNotifier<ConfirmTransaksiState> {
  final Ref ref;
  ConfirmTransaksiNotifier({
    required this.ref,
  }) : super(ConfirmTransaksiStateInit());

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

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

//provider
final confirmTransaksiProvider =
    StateNotifierProvider<ConfirmTransaksiNotifier, ConfirmTransaksiState>(
  (ref) => ConfirmTransaksiNotifier(ref: ref),
);
