import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:generp/Models/ordersModels/paymentListByModeFilterResponse.dart';
import 'package:generp/Models/ordersModels/paymentListByModeResponse.dart';
import 'package:provider/provider.dart';

import '../../Models/ordersModels/paymentDetailsByModeFilterResponse.dart';
import '../../Utils/commonServices.dart';
import '../../services/api_calling.dart';
import '../HomeScreenNotifier.dart';

class Paymentsprovider extends ChangeNotifier {
  bool _showMoreDetails = false;
  bool _submitLoading = false;
  TextEditingController approvalRejectionController = TextEditingController();
  TextEditingController adjustedAddAmountController = TextEditingController();

  String? approvalRejectionError;
  String? adjustedAddAmountError;
  String? selectedAccountError;

  List<Employees> _employeesList = [];
  List<OrderList> _paymentsList = [];
  Employees? _selectedEmployee;
  String? _selectedEmpID;
  String? _selectedEmpName;
  bool _isLoading = true;
  PaymentDetails _paymentsDetails = PaymentDetails();
  List<PaidList> _paidLists = [];
  List<String> _headings = [];
  List<String> _subHeadings = [];

  PaymentDetails get paymentDetails => _paymentsDetails;

  List<PaidList> get paidLists => _paidLists;
  PaidList? _selectedPaidList;
  String? _selectedPaidOrderId;
  String? _selectedPaidOrderValue;
  PaidList? get selectedPaidList => _selectedPaidList;
  String? get selectedPaidOrderId => _selectedPaidOrderId;
  String? get selectedPaidOrderValue => _selectedPaidOrderValue;

  set selectedPaidList(PaidList? value) {
    _selectedPaidList = value;
    _selectedPaidOrderId = value!.id;
    _selectedPaidOrderValue = value.orderNumber;
    notifyListeners();
  }

  set selectedPaidOrderId(String? value) {
    _selectedPaidOrderId = value;
    notifyListeners();
  }

  set selectedPaidOrderValue(String? value) {
    _selectedPaidOrderValue = value;
    notifyListeners();
  }

  List<String> get Headings => _headings;

  bool get showMoreDetails => _showMoreDetails;
  bool get submitLoading => _submitLoading;

  List<String> get subHeadings => _subHeadings;

  List<Employees> get employeesList => _employeesList;

  List<OrderList> get paymentsList => _paymentsList;

  Employees? get selectedEmployee => _selectedEmployee;

  String? get selectedEmpID => _selectedEmpID;

  String? get selectedEmpName => _selectedEmpName;

  bool get isLoading => _isLoading;

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

  set selectedEmployee(Employees? value) {
    _selectedEmployee = value;
    _selectedEmpID = value?.id!;
    _selectedEmpName = value!.name!;
    notifyListeners();
  }

  set selectedEmpID(String? value) {
    _selectedEmpID = value;
    notifyListeners();
  }

  set selectedEmpName(String? value) {
    _selectedEmpName = value;
    notifyListeners();
  }

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

  Future<void> paymentsListsByModeFilterAPIFunction(context, mode) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.paymentListByModeFilterAPI(
        provider.empId,
        provider.session,
        mode,
      );
      if (data != null) {
        if (data.error == "0") {
          _employeesList = data.employees!;
          notifyListeners();
        } else {}
      }
    } catch (e) {}
  }

  bool _isLoadingMore = false;
  bool get isLoadingMore => _isLoadingMore;

  bool _hasMoreData = true;
  bool get hasMoreData => _hasMoreData;

  int _currentPage = 1;
  String? _errorMessage;
  String? get errorMessage => _errorMessage;

  void resetPagination() {
    _paymentsList.clear();
    _currentPage = 1;
    _hasMoreData = true;
    _isLoading = false;
    _isLoadingMore = false;
    _errorMessage = null;
    notifyListeners();
  }

  Future<void> paymentsListsByModeAPIFunction(
    BuildContext context,
    String mode,
    String teamEmployee, {
    bool append = false,
  }) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);

      if (!append) {
        _isLoading = true;
        _errorMessage = null;
        notifyListeners();
      } else {
        _isLoadingMore = true;
        notifyListeners();
      }

      final data = await ApiCalling.paymentListsByModeAPI(
        provider.empId,
        provider.session,
        mode,
        teamEmployee,
        _currentPage.toString(),
      );
      debugPrint(
        'empId: ${provider.empId}, session: ${provider.session}, pageNumber: $_currentPage',
      );

      if (data != null && data.error == "0") {
        if (append) {
          _paymentsList.addAll(data.orderList ?? []);
        } else {
          _paymentsList = data.orderList ?? [];
        }

        if (data.orderList == null || data.orderList!.length < 10) {
          _hasMoreData = false;
        }
      } else {
        if (!append) _errorMessage = "No payments found!";
        _hasMoreData = false;
      }
    } catch (e) {
      _errorMessage = "Error: $e";
    }

    _isLoading = false;
    _isLoadingMore = false;
    notifyListeners();
  }

  Future<void> loadMore(
    BuildContext context,
    String mode,
    String teamEmployee,
  ) async {
    if (_isLoadingMore || !_hasMoreData) return;
    _currentPage++;
    await paymentsListsByModeAPIFunction(
      context,
      mode,
      teamEmployee,
      append: true,
    );
  }

  Future<void> paymentsDetailsByModeAPIFunction(
    context,
    paymentId,
    mode,
  ) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.paymentsDetailsByModeAPI(
        provider.empId,
        provider.session,
        paymentId,
      );
      if (data != null) {
        _isLoading = true;
        notifyListeners();
        if (data.error == "0") {
          _paymentsDetails = data.paymentDetails!;
          _paidLists = data.paidList!;
          _headings = [
            "Account Name",
            "Entered By",
            "Payment Type",
            "Payment Reference Number",
            "Payment Date",
            "Adjusted Amount",
            "Amount",
            "Description",
            "Approved Employee",
            "Approved Remarks",
            "Attachment",
            "Created Datetime",
            "Description",
            "Status",
          ];
          _subHeadings = [
            _paymentsDetails.accountName ?? "-",
            _paymentsDetails.enteredEmpName ?? "-",
            _paymentsDetails.paymentType ?? "-",
            _paymentsDetails.refNo ?? "-",
            _paymentsDetails.paymentDate ?? "-",
            _paymentsDetails.adjustedAmount ?? "-",
            _paymentsDetails.amount ?? "-",
            _paymentsDetails.description ?? "-",
            _paymentsDetails.approvalEmployee ?? "-",
            _paymentsDetails.approvalEmployee ?? "-",
            _paymentsDetails.attachmentViewFileName ?? "-",
            _paymentsDetails.datetime ?? "-",
            _paymentsDetails.status ?? "-",
          ];

          _isLoading = false;
        } else {
          _isLoading = false;
        }
        notifyListeners();
      }
    } catch (e) {}
  }

  Future<void> paymentApprovalRejectionAPIFunction(
    context,
    paymentId,
    type,
  ) async {
    try {
      if (!validateApprovalRejectionForm(context)) {
        return;
      }
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.paymentOrderApproveRejectAPI(
        provider.empId,
        provider.session,
        paymentId,
        type,
        approvalRejectionController.text,
      );
      if (data != null) {
        if (data.error == "0") {
          toast(context, "${data.message}");
          resetForm();
          Navigator.pop(context, true);
          notifyListeners();
        }
      }
    } catch (e) {}
  }

  Future<void> paymentDeletionAPIFunction(context, paymentId) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.paymentOrderDeleteAPI(
        provider.empId,
        provider.session,
        paymentId,
      );
      if (data != null) {
        if (data.error == "0") {
          toast(context, "${data.message}");
          resetForm();
          Navigator.pop(context, true);
          Navigator.pop(context, true);
          notifyListeners();
        }
      }
    } catch (e) {}
  }

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

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

  bool validateApprovalRejectionForm(BuildContext context) {
    bool isValid = true;
    approvalRejectionError = null;
    if (approvalRejectionController.text.trim().isEmpty) {
      approvalRejectionError = "Please Enter Remarks";
      isValid = false;
    }
    notifyListeners();
    return isValid;
  }

  void onChangeApprovalRejection(value) {
    approvalRejectionError = "";
    notifyListeners();
  }

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

  void resetForm() {
    _submitLoading = false;
    adjustedAddAmountController.clear();
    approvalRejectionController.clear();
    approvalRejectionError = "";
    adjustedAddAmountError = null;
    notifyListeners();
  }

  void resetAll() {
    _submitLoading = false;
    approvalRejectionController.clear();
    approvalRejectionError = "";
    adjustedAddAmountController.clear();
    adjustedAddAmountError = null;
    _selectedEmployee = null;
    _selectedEmpID = "";
    _selectedEmpName = "";
    _selectedPaidList = null;
    _selectedPaidOrderId = null;
    _selectedPaidOrderValue = null;

    checkdropDownReset();
    notifyListeners();
  }

  checkdropDownReset() {
    if (_selectedPaidList != null && !_paidLists.contains(_selectedPaidList)) {
      _selectedPaidList = null;
      _selectedPaidOrderId = null;
      _selectedPaidOrderValue = null;
    }
    notifyListeners();
  }
}
