import 'package:flutter/cupertino.dart';
import 'package:generp/Notifiers/HomeScreenNotifier.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/services/api_calling.dart';
import 'package:provider/provider.dart';

import '../../Models/ordersModels/EditPaymentDetailsAdjustedOrdersViewResponse.dart';
import 'addPaymentProvider.dart';

class Editpaymentprovider extends ChangeNotifier {
  bool _submitLoading = false;
  List<PaidList> _paidList = [];
  List<EditOrderList> _editOrderList = [];

  PaidList? _selectedPaidList;
  EditOrderList? _selectedOrderList;

  List<TextEditingController> editOrderAmountControllers = [];
  List<TextEditingController> editOrderAmountControllers2 = [];
  List<String?> _selectedPaidOrderIDs = [];
  List<String?> _selectedOrderIDs = [];

  List<Map<String, String>> _insertAmounts = [];
  List<Map<String, String>> _updateAmounts = [];

  List<PaidList> get paidList => _paidList;

  List<EditOrderList> get editOrderList => _editOrderList;

  PaidList? get selectedPaidList => _selectedPaidList;

  EditOrderList? get selectedOrderList => _selectedOrderList;

  List<String?> get selectedPaidOrderIDs => _selectedPaidOrderIDs;

  List<String?> get selectedOrderIDs => _selectedOrderIDs;

  bool get submitLoading => _submitLoading;

  set selectedPaidOrderIDs(List<String?> value) {
    _selectedPaidOrderIDs = value;
    notifyListeners();
  }

  set selectedOrderIDs(List<String?> value) {
    _selectedOrderIDs = value;
    notifyListeners();
  }

  set selectedPaidList(PaidList? value) {
    _selectedPaidList = value;
    notifyListeners();
  }

  set selectedOrderList(EditOrderList? value) {
    _selectedOrderList = value;
    notifyListeners();
  }

  set submitLoading(bool value) {
    _submitLoading = value;
    notifyListeners();
  }

  void updateSelectedPaidOrderId(int index, PaidList? value) {
    _selectedPaidList = value!;

    _selectedPaidOrderIDs[index] = value!.orderId;
    print(_selectedPaidOrderIDs[index]);
    notifyListeners();
  }

  void updateSelectedOrderId(int index, EditOrderList? value) {
    _selectedOrderList = value!;
    print(index);
    print(value);
    print(value!.orderId);
    if (index > 0) {
      _selectedOrderIDs[index] = value!.orderId;
      print(_selectedOrderIDs[index]);
    } else {
      _selectedOrderIDs[0] = value!.orderId;
      print(_selectedOrderIDs[0]);
    }

    notifyListeners();
  }

  void editAddNewRow() {
    editOrderAmountControllers.add(TextEditingController());
    _selectedPaidOrderIDs.add(null);

    notifyListeners();
  }

  void editAddNewRow2() {
    editOrderAmountControllers2.add(TextEditingController());
    _selectedOrderIDs.add(null);

    notifyListeners();
  }

  void editRemoveRow(int index) {
    editOrderAmountControllers[index].dispose();
    editOrderAmountControllers.removeAt(index);
    _selectedPaidOrderIDs.removeAt(index);
    notifyListeners();
  }

  void editRemoveRow2(int index) {
    editOrderAmountControllers2[index].dispose();
    editOrderAmountControllers2.removeAt(index);
    _selectedOrderIDs.removeAt(index);
    notifyListeners();
  }

  // List<Map<String, String>> getFormData() {
  //   _insertAmounts = [];
  //   Map<String, String> latestEntries = {};
  //   for (int i = 0; i < _selectedOrderIDs.length; i++) {
  //     final rowData = {
  //       "selected_order_id": _selectedOrderIDs.toString(),
  //       "insert_amount": editOrderAmountControllers2[i].text.toString(),
  //
  //
  //     };
  //     _updateAmounts.add(rowData);
  //   }
  //
  //   _insertAmounts = latestEntries.entries
  //       .map((entry) =>
  //   {
  //     "selected_order_id": entry.key,
  //     "insert_amount": entry.value,
  //   })
  //       .toList();
  //
  //   print("Form Data: $_insertAmounts");
  //   notifyListeners();
  //   return _insertAmounts;
  // }
  List<Map<String, String>> getFormData() {
    _insertAmounts = [];
    Map<String, String> latestEntries = {};
    for (int i = 0; i < editOrderAmountControllers2.length; i++) {
      if (_selectedOrderIDs[i] != null &&
          editOrderAmountControllers2[i].text.isNotEmpty) {
        latestEntries[_selectedOrderIDs[i]!] =
            editOrderAmountControllers2[i].text;
      }
    }

    _insertAmounts =
        latestEntries.entries
            .map(
              (entry) => {
                "selected_order_id": entry.key,
                "insert_amount": entry.value,
              },
            )
            .toList();

    print("Form Data: $_insertAmounts");
    notifyListeners();
    return _insertAmounts;
  }

  // List<Map<String, String>> getFormData() {
  //   _insertAmounts = [];
  //   for (int i = 0; i < _selectedOrderIDs.length; i++) {
  //     if (_selectedOrderIDs[i] != null && editOrderAmountControllers2[i].text.isNotEmpty) {
  //       final rowData = {
  //         "selected_order_id": _selectedOrderIDs[i]!,
  //         "insert_amount": editOrderAmountControllers2[i].text,
  //       };
  //       _insertAmounts.add(rowData);
  //     }
  //   }
  //   print("Form Data: $_insertAmounts");
  //   notifyListeners();
  //   return _insertAmounts;
  // }

  List<Map<String, String>> getFormDataUpdate() {
    _updateAmounts = [];
    for (int i = 0; i < _paidList.length; i++) {
      final rowData = {
        "order_id": _paidList[i]!.orderId.toString(),
        "order_payment_id": _paidList[i]!.orderPaymentId.toString(),
        "selected_order_id": _paidList[i]!.orderId.toString(),
        "updateable_payment_amount": _paidList[i]!.adjustedAmount.toString(),
      };
      _updateAmounts.add(rowData);
    }
    print("Form Data: $_updateAmounts");
    notifyListeners();
    return _updateAmounts;
  }

  Future<void> editPaymentDetailsAPIFunction(
    context,
    payment_id,
    description,
    payment_type,
    ref_no,
    payment_date,
    amount,
  ) async {
    try {
      _submitLoading = true;
      notifyListeners();
      final provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final addOrderProvider = Provider.of<Addpaymentprovider>(
        context,
        listen: false,
      );
      final data = await ApiCalling.ordersEditPaymentDetailsAPI(
        provider.empId,
        provider.session,
        payment_id,
        description,
        payment_type,
        ref_no,
        payment_date,
        amount,
      );
      if (data != null) {
        if (data.error == "0") {
          _submitLoading = false;
          addOrderProvider.resetForm();
          Navigator.pop(context,true);
          toast(context, data.message);
          notifyListeners();
        } else if (data.error == "1") {
          _submitLoading = false;
          notifyListeners();
        }
      } else {
        _submitLoading = false;
        notifyListeners();
      }
    } catch (e, s) {
      _submitLoading = false;
      notifyListeners();
    }
  }

  Future<void> editPaymentDetailsAdjustedOrdersViewAPIFunction(
    context,
    payment_id,
  ) async {
    try {
      print("payment_id: ${payment_id}");
      final provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data =
          await ApiCalling.ordersEditPaymentDetailsAdjustedOrdersViewAPI(
            provider.empId,
            provider.session,
            payment_id,
          );
      if (data != null) {
        if (data.error == "0") {
          _editOrderList = data.editOrderList!;
          _paidList = data.paidList!;

          getFormDataUpdate();
          notifyListeners();
        } else if (data.error == "1") {}
      } else {}
    } catch (e, s) {}
  }

  Future<void> editPaymentDetailsAdjustedOrdersUpdateAPIFunction(
    context,
    payment_id,
    update_amounts,
    insert_amounts,
  ) async {
    try {
      _submitLoading = true;
      notifyListeners();
      final provider = Provider.of<HomescreenNotifier>(context, listen: false);

      final data =
          await ApiCalling.ordersEditPaymentDetailsAdjustedOrdersUpdateAPI(
            provider.empId,
            provider.session,
            payment_id,
            update_amounts,
            insert_amounts,
          );
      if (data != null) {
        if (data.error == "0") {
          _submitLoading = false;
          resetForm();
          Navigator.pop(context,true);
          toast(context, data.message);
          notifyListeners();
        } else if (data.error == "1") {
          _submitLoading = false;
          notifyListeners();
        }
      } else {
        _submitLoading = false;
        notifyListeners();
      }
    } catch (e, s) {
      _submitLoading = false;
      notifyListeners();
    }
  }

  void checkDropdownselected() {
    if (_selectedOrderList != null &&
        !_editOrderList.contains(_selectedOrderList)) {
      selectedOrderList = null;
      _selectedOrderIDs.clear();
    }
    if (_selectedPaidList != null && !_paidList.contains(_selectedPaidList)) {
      _selectedPaidList = null;
      _selectedPaidOrderIDs.clear();
    }
  }

  void resetForm() {
    _submitLoading =false;
    checkDropdownselected();
    _selectedPaidList = null;
    _selectedOrderList = null;
    _selectedOrderIDs.clear();
    _selectedPaidOrderIDs.clear();
    editOrderAmountControllers.forEach((controller) => controller.dispose());
    editOrderAmountControllers2.forEach((controller) => controller.dispose());
    editOrderAmountControllers.clear();
    editOrderAmountControllers2.clear();
  }
}
