import 'package:flutter/widgets.dart';
import 'package:initial_folder/models/history_transaction_model.dart';
import 'package:initial_folder/services/history_transactions_service.dart';

enum ResultState { loading, noData, hasData, error }

class HistoryTranscationsProvider with ChangeNotifier {
  HistoryTranscationsProvider({required this.historyTransactionService}) {
    getHistoryTransaction();
  }

  final HistoryTransactionService historyTransactionService;

  ResultState? _state;
  String _message = '';
  List<HistoryTransactionModel>? _historyTransactionsModel;
  List<HistoryTransactionModel>? get historyPayment {
    return _historyTransactionsModel == null
        ? []
        : _historyTransactionsModel!
            .where((element) => element.statusPayment != '2')
            .toList();
  }

  List<HistoryTransactionModel>? get paymentPending {
    return _historyTransactionsModel == null
        ? []
        : _historyTransactionsModel!
            .where((element) => element.statusPayment == '2')
            .toList();
  }

  // transaksi dengan status "-5" 
  List<HistoryTransactionModel>? get paymentAwaitingMethod {
    return _historyTransactionsModel == null
        ? []
        : _historyTransactionsModel!
            .where((element) => element.statusPayment == '-5')
            .toList();
  }

  ResultState? get state => _state;
  String get message => _message;

  set histtoryTranscation(List<HistoryTransactionModel> historyTr) {
    _historyTransactionsModel = historyTr;
    notifyListeners();
  }

  Stream<List<HistoryTransactionModel>> getHistoryTransactionStream() async* {
    while (true) {
      List<HistoryTransactionModel>? response =
          await historyTransactionService.historyTransactions();

      if (response.isNotEmpty) {
        yield response
            .where((transaction) => transaction.statusPayment == '2')
            .toList();
      }
    }
  }

  Future<dynamic> getHistoryTransaction() async {
    try {
      _state = ResultState.loading;
      notifyListeners();
      List<HistoryTransactionModel>? response =
          await historyTransactionService.historyTransactions();
      if (response.isEmpty) {
        _state = ResultState.noData;
        notifyListeners();
        return _message = 'Tidak Ada data';
      } else {
        _state = ResultState.hasData;
        notifyListeners();
        return _historyTransactionsModel = response;
      }
    } catch (e) {
      _state = ResultState.error;
      notifyListeners();
      return _message = 'Data transaksi gagal diambil';
    }
  }
}
