import 'package:flutter/foundation.dart';
import 'package:generp/Notifiers/HomeScreenNotifier.dart';
import 'package:generp/services/api_calling.dart';
import 'package:provider/provider.dart';

import '../../Models/commonModels/commonAccountdetailsResponse.dart';

class Accountdetailsprovider extends ChangeNotifier {
  bool _showMoreDetails = false;

  AccountDetails _accountDetails = AccountDetails();
  BalanceDetails _balanceDetails = BalanceDetails();
  List<LedgerList> _ledgerList = [];

  bool get showMoreDetails => _showMoreDetails;
  AccountDetails get accountDetails => _accountDetails;
  BalanceDetails get balanceDetails => _balanceDetails;
  List<LedgerList> get ledgerList => _ledgerList;
  double totalCredit = 0.0;
  double totalDebit = 0.0;
  double totalRunningBalance = 0.0;
  List<double> runningBalances = [];

  set showMoreDetails(bool value) {
    _showMoreDetails = value;
    notifyListeners();
  }

  Future<void> accountdetailsAPIFunction(context, accountID) async {
    try {
      var prov = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.commonAccountDetailsAPI(
        prov.empId,
        prov.session,
        accountID,
      );
      if (data != null) {
        if (data.error == "0") {
          _accountDetails = data.accountDetails!;
          _balanceDetails = data.balanceDetails!;
          _ledgerList = data.ledgerList!;
          for (var item in _ledgerList) {
            double credit = double.tryParse(item.creditAmount.toString()) ?? 0;
            double debit = double.tryParse(item.debitAmount.toString()) ?? 0;
            totalCredit = 0.0;
            totalDebit = 0.0;
            totalRunningBalance = 0.0;
            runningBalances = [];

            totalCredit += credit;
            totalDebit += debit;
            totalRunningBalance += (debit - credit);
            runningBalances.add(totalRunningBalance);
          }
          notifyListeners();
        }
      }
    } catch (e) {}
  }

  Map<String, List<LedgerList>> groupByDate(List<LedgerList> list) {
    Map<String, List<LedgerList>> grouped = {};

    for (var item in list) {
      String date = item.createdDatetime!;
      if (!grouped.containsKey(date)) {
        grouped[date] = [];
      }
      grouped[date]!.add(item);
    }

    return grouped;
  }

  void resetValues() {
    totalCredit = 0.0;
    totalDebit = 0.0;
    totalRunningBalance = 0.0;
    runningBalances = [];
  }
}
