import 'package:flutter/cupertino.dart';
import 'package:generp/Notifiers/HomeScreenNotifier.dart';
import 'package:generp/Notifiers/ordersProvider/paymentsProvider.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;
  TextEditingController adjustedAddAmountController = TextEditingController();

  String? approvalRejectionError;
  String? adjustedAddAmountError;
  String? selectedAccountError;
  List<EditPaidList> _paidList = [];
  final List<EditOrderList> _editOrderList = [];

  EditPaidList? _selectedPaidLists;
  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<EditPaidList> get paidList => _paidList;

  List<EditOrderList> get editOrderList => _editOrderList;

  EditPaidList? get selectedPaidLists => _selectedPaidLists;

  EditOrderList? get selectedOrderList => _selectedOrderList;

  List<String?> get selectedPaidOrderIDs => _selectedPaidOrderIDs;

  List<String?> get selectedOrderIDs => _selectedOrderIDs;

  bool get submitLoading => _submitLoading;
  final List<EditPaidList> _editpaidLists = [];
  List<EditPaidList> get editpaidLists => _editpaidLists;
  EditPaidList? _editselectedPaidList;
  String? _editselectedPaidOrderId;
  String? _editselectedPaidOrderValue;
  EditPaidList? get editselectedPaidList => _editselectedPaidList;
  String? get editselectedPaidOrderId => _editselectedPaidOrderId;
  String? get editselectedPaidOrderValue => _editselectedPaidOrderValue;

  set editselectedPaidList(EditPaidList? value) {
    _editselectedPaidList = value;
    _editselectedPaidOrderId = value!.orderId;
    _editselectedPaidOrderValue = value.orderNumber;
    notifyListeners();
  }

  set editselectedPaidOrderId(String? value) {
    _editselectedPaidOrderId = value;
    notifyListeners();
  }

  set editselectedPaidOrderValue(String? value) {
    _editselectedPaidOrderValue = value;
    notifyListeners();
  }

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

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

  set selectedPaidLists(EditPaidList? value) {
    _selectedPaidLists = value;
    notifyListeners();
  }

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

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

  void updateSelectedPaidOrderId(int index, EditPaidList? value) {
    _selectedPaidLists = 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,
    paymentId,
    description,
    paymentType,
    refNo,
    paymentDate,
    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,
        paymentId,
        description,
        paymentType,
        refNo,
        paymentDate,
        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) {
      _submitLoading = false;
      notifyListeners();
    }
  }

  Future<void> editPaymentDetailsAdjustedOrdersViewAPIFunction(
    context,
    paymentId, [
    index,
  ]) async {
    try {
      print("payment_id: $paymentId");
      final provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data =
          await ApiCalling.ordersEditPaymentDetailsAdjustedOrdersViewAPI(
            provider.empId,
            provider.session,
            paymentId,
          );
      if (data != null) {
        if (data.error == "0") {
          _paidList = data.paidList!;
          if (index != null) {
            adjustedAddAmountController.text =
                data.paidList![index].orderAmount!;
            _editselectedPaidList = data.paidList![index];
            _editselectedPaidOrderId = data.paidList![index].orderId;
          }

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

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

      final data =
          await ApiCalling.ordersEditPaymentDetailsAdjustedOrdersUpdateAPI(
            provider.empId,
            provider.session,
            paymentId,
            updateAmounts,
            insertAmounts,
          );
      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) {
      _submitLoading = false;
      notifyListeners();
    }
  }

  Future<void> paymentsDetailsAddAdjustedOrderModeAPIFunction(
    context,
    paymentId,
    selectedOrderId,
    mode,
  ) async {
    try {
      if (!validate()) {
        return;
      }
      _submitLoading = true;
      notifyListeners();
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      var pprovider = Provider.of<Paymentsprovider>(context, listen: false);
      final data = await ApiCalling.paymentsDetailsAddAdjustedOrderAPI(
        provider.empId,
        provider.session,
        paymentId,
        selectedOrderId,
        adjustedAddAmountController.text,
      );
      if (data != null) {
        if (data.error == "0") {
          _submitLoading = false;
          toast(context, "${data.message}");
          resetAll();
          Navigator.pop(context, true);
          pprovider.paymentsDetailsByModeAPIFunction(context, paymentId, mode);
          notifyListeners();
        } else {
          _submitLoading = false;
          notifyListeners();
        }
      } else {
        _submitLoading = false;
        notifyListeners();
      }
    } catch (e) {
      _submitLoading = false;
      notifyListeners();
    }
  }

  Future<void> paymentsDetailsEditAdjustedOrderModeAPIFunction(
    context,
    orderPaymentId,
    selectedOrderId,
    mode,
    paymentId,
  ) async {
    try {
      print(
        "$selectedOrderId , ${adjustedAddAmountController.text} , $orderPaymentId,",
      );
      if (!validate()) {
        return;
      }
      _submitLoading = true;
      notifyListeners();
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      var pprovider = Provider.of<Paymentsprovider>(context, listen: false);
      final data = await ApiCalling.paymentsDetailsEditAdjustedOrderAPI(
        provider.empId,
        provider.session,
        selectedOrderId,
        adjustedAddAmountController.text,
        orderPaymentId,
      );

      if (data != null) {
        if (data.error == "0") {
          toast(context, "${data.message}");
          resetAll();
          Navigator.pop(context, true);
          pprovider.paymentsDetailsByModeAPIFunction(context, paymentId, mode);
          notifyListeners();
        } else {
          _submitLoading = false;
          notifyListeners();
        }
      } else {
        _submitLoading = false;
        notifyListeners();
      }
    } catch (e) {
      _submitLoading = false;
    }
  }

  onChnageAmountController(value) {
    adjustedAddAmountError = null;
    notifyListeners();
  }

  bool validate() {
    bool isValid = true;
    adjustedAddAmountError = null;
    selectedAccountError = null;

    if (_editselectedPaidList == null || _editselectedPaidOrderId == null) {
      selectedAccountError = "Please Select a Value";
      isValid = false;
    }
    if (adjustedAddAmountController.text.trim().isEmpty) {
      adjustedAddAmountError = "Please enter Amount";
      isValid = false;
    }
    _submitLoading = false;
    notifyListeners();
    return isValid;
  }

  void resetAll() {
    _submitLoading = false;
    approvalRejectionError = "";
    adjustedAddAmountController.clear();
    adjustedAddAmountError = null;
    _editselectedPaidList = null;
    _editselectedPaidOrderId = null;
    _editselectedPaidOrderValue = null;

    checkdropDownReset();
    notifyListeners();
  }

  checkdropDownReset() {
    if (_editselectedPaidList != null &&
        !_editpaidLists.contains(_editselectedPaidList)) {
      _editselectedPaidList = null;
      _editselectedPaidOrderId = null;
      _editselectedPaidOrderValue = null;
    }
    notifyListeners();
  }

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

  void resetForm() {
    _submitLoading = false;
    checkDropdownselected();
    _editselectedPaidList = null;
    _selectedOrderList = null;
    _selectedOrderIDs.clear();
    _selectedPaidOrderIDs.clear();
    for (var controller in editOrderAmountControllers) {
      controller.dispose();
    }
    for (var controller in editOrderAmountControllers2) {
      controller.dispose();
    }
    editOrderAmountControllers.clear();
    editOrderAmountControllers2.clear();
  }
}
