import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:generp/Models/financeModels/paymentRequisitionDetailsResponse.dart';
import 'package:generp/Notifiers/HomeScreenNotifier.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/services/api_calling.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

import 'approveRejectPaymentRequestResponse.dart';

class Requesitionlidtdetailsprovider extends ChangeNotifier {
  TextEditingController requestedAmount = TextEditingController();
  TextEditingController approvedAmountReadonly = TextEditingController();
  TextEditingController proposedPaymentAccount = TextEditingController();
  TextEditingController approvedAmount = TextEditingController();
  TextEditingController accountName = TextEditingController();
  TextEditingController branch = TextEditingController();
  TextEditingController requestingPurpose = TextEditingController();
  TextEditingController description = TextEditingController();
  TextEditingController amount = TextEditingController();
  TextEditingController paymentMode = TextEditingController();
  TextEditingController bankUpiID = TextEditingController();
  TextEditingController bankName = TextEditingController();
  TextEditingController bankBranchName = TextEditingController();
  TextEditingController bankAccountNumber = TextEditingController();
  TextEditingController bankIfscCode = TextEditingController();
  TextEditingController bankHolderName = TextEditingController();
  TextEditingController paymentAccountSearchController =
  TextEditingController();
String? proposedAmountError;
  PaymentDetails _paymentDetails = PaymentDetails();
  RequestDetails _requestDetails = RequestDetails();
  PaymentRequestDetails _paymentRequestDetails = PaymentRequestDetails();
  PaymentAccounts? _selectedPaymentAccounts;

  List<PaymentModes> _paymentModes = [];
  List<PaymentAccounts> _paymentAccounts = [];

  var _selectedValue;
  var _selectedID;

  List<String> _headings = [];
  List<String> _subHeadings = [];

  String? FileError;
  var _image_picked = 0;
  final ImagePicker _picker = ImagePicker();

  File? _image;
  File? _imageName;

  get image_picked => _image_picked;

  int get imagePicked => _image_picked;

  File? get imagePath => _imageName;

  File? get imageFilePath => _image;

  set imagePicked(int value) {
    _image_picked = value;
    notifyListeners();
  }

  set imagePath(File? value) {
    _imageName = value;
    notifyListeners();
  }

  set imageFilePath(File? value) {
    _image = value;
    notifyListeners();
  }

  PaymentDetails get paymentsDetails => _paymentDetails;

  RequestDetails get requestsDetails => _requestDetails;

  List<PaymentAccounts> get paymentsAccounts => _paymentAccounts;

  List<PaymentModes> get paymentsModes => _paymentModes;

  PaymentRequestDetails get paymentsReqDetails => _paymentRequestDetails;

  PaymentAccounts? get selectedPaymentAccounts => _selectedPaymentAccounts;

  get selectedValue => _selectedValue;

  get selectedID => _selectedID;

  List<String> get subHeadings => _subHeadings;

  set subHeadings(List<String> value) {
    _subHeadings = value;
    notifyListeners();
  }

  List<String> get Headings => _headings;

  set selectedPaymentAccounts(PaymentAccounts? value) {
    _selectedPaymentAccounts = value;
    _selectedValue = value!.name!;
    _selectedID = value!.id;
    notifyListeners();
  }

  set selectedValue(value) {
    _selectedValue = value;
    notifyListeners();
  }

  set selectedID(value) {
    _selectedID = value;
    notifyListeners();
  }

  imgFromCamera(context) async {
    // Capture a photo
    try {
      final XFile? galleryImage = await _picker.pickImage(
        source: ImageSource.camera,
        imageQuality: 50,
      );
      debugPrint("added");

      _image = File(galleryImage!.path);
      _imageName = File(galleryImage!.name);
      _image_picked = 1;
      FileError = null;
      notifyListeners();
    } catch (e) {
      debugPrint("mmmm: ${e.toString()}");
    }
  }

  imgFromGallery(context) async {
    // Pick an image
    try {
      final XFile? galleryImage = await _picker.pickImage(
        source: ImageSource.gallery,
      );
      final bytes = (await galleryImage?.readAsBytes())?.lengthInBytes;
      final kb = bytes! / 1024;
      final mb = kb / 1024;

      debugPrint("Jenny: bytes:$bytes, kb:$kb, mb: $mb");

      _image = File(galleryImage!.path);
      _imageName = File(galleryImage!.name);
      _image_picked = 1;
      FileError = null;
      notifyListeners();
      // var file = FlutterImageCompress.compressWithFile(galleryImage!.path);
    } catch (e) {
      debugPrint("mmmm: ${e.toString()}");
    }
  }

  Future<void> paymentRequesitionDetails(context, payment_request_id) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.paymentRequestionDetailsAPI(
        provider.empId,
        provider.session,
        payment_request_id,
      );
      if (data != null) {
        if (data.error == "0") {
          _headings = [
            "Requested Account",
            "Proposed Account Name",
            "Branch",
            "Requesting Propose",
            "Payment Mode",
            "Created Employee",
            "Attachment",
            "Requested Date",
            "Note",
            "Level 1 Remarks",
            "Level 1 Approved By",
            "Level 2 Remarks",
            "Level 2 Approved By",
            "Approved Amount",
            "Created Date/Time",
            "Updated Date/Time",
          ];
          _paymentDetails =
              data.paymentDetails ??
                  PaymentDetails(
                    accountId: "-",
                    accountName: "-",
                    amount: "-",
                    attachmentDirFilePath: "-",
                    attachmentViewFileName: "-",
                    bankAccountHolderName: "-",
                    bankAccountNumber: "-",
                    bankBranchName: "-",
                    bankIfscCode: "-",
                    bankName: "-",
                    bankUpiId: "-",
                    createdDatetime: "-",
                    createdEmployeeId: "-",
                    description: "-",
                    id: "-",
                    isExists: "-",
                    mode: "-",
                    paymentAccountId: "-",
                    paymentAccountName: "-",
                    paymentDate: "-",
                    paymentEmployeeName: "-",
                    paymentModeId: "-",
                    paymentReferenceNumber: "-",
                    paymentRemarks: "-",
                    refId: "-",
                    refType: "-",
                    updatedDatetime: "-",
                  );

          _requestDetails =
              data.requestDetails ??
                  RequestDetails(
                    updatedDatetime: "-",
                    id: "-",
                    description: "-",
                    createdDatetime: "-",
                    attachmentViewFileName: "-",
                    attachmentDirFilePath: "-",
                    amount: "-",
                    accountName: "-",
                    accountId: "-",
                    branch: "-",
                    createdEmployee: "-",
                    date: "-",
                    isProcessedPaymentRequest: "-",
                    level1ApprovalRemarks: "-",
                    level1Employee: "-",
                    level2ApprovalRemarks: "-",
                    level2Employee: "-",
                    proposedAccount: "-",
                    proposedAccountId: "-",
                    requestedAmount: "-",
                    requestingPurpose: "-",
                    requestMode: "-",
                    status: "-",
                    transDis: "-",
                  );

          _subHeadings = [
            _requestDetails.accountName ?? "-",
            _requestDetails.proposedAccount ?? "-",
            _requestDetails.branch ?? "-",
            _requestDetails.requestingPurpose ?? "-",
            _requestDetails.requestMode ?? "-",
            _requestDetails.createdEmployee ?? "-",
            _requestDetails.attachmentViewFileName ?? "-",
            _requestDetails.date ?? "-",
            _requestDetails.description ?? "-",
            _requestDetails.level1ApprovalRemarks ?? "-",
            _requestDetails.level1Employee ?? "-",
            _requestDetails.level2ApprovalRemarks ?? "-",
            _requestDetails.level2Employee ?? "-",
            _requestDetails.amount ?? "-",
            _requestDetails.createdDatetime ?? "-",
            _requestDetails.updatedDatetime ?? "-",
          ];

          print("here 2121");
          preValues();
          notifyListeners();
        }
      }
    } catch (e, s) {}
  }

  preValues() {
    print("here 212ssass1");
    requestedAmount.text = _requestDetails.requestedAmount ?? "-";
    proposedPaymentAccount.text = _requestDetails.proposedAccount ?? "-";
    approvedAmountReadonly.text = _requestDetails.formattedAmount ?? "-";
    approvedAmount.text = _requestDetails.amount ?? "-";
    accountName.text = _requestDetails.accountName ?? "-";
    branch.text = _requestDetails.branch ?? "-";
    requestingPurpose.text = _requestDetails.requestingPurpose ?? "-";
    description.text = _requestDetails.description ?? "-";
    amount.text = _requestDetails.amount ?? "-";
    paymentMode.text = _requestDetails.requestMode ?? "-";
    bankUpiID.text = _requestDetails.bankUpiId ?? "-";
    bankName.text = _requestDetails.bankName ?? "-";
    bankBranchName.text = _requestDetails.bankBranchname ?? "-";
    bankAccountNumber.text = _requestDetails.bankAccountNumber ?? "-";
    bankIfscCode.text = _requestDetails.bankIfscCode ?? "-";
    bankHolderName.text = _requestDetails.bankAccountHolderName ?? "-";
    notifyListeners();
  }

  Future<void> approveRejectPaymentRequestAPIFunction(context,
      payment_request_id,) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.approveRejectPaymentRequestAPI(
        provider.empId,
        provider.session,
        payment_request_id,
      );
      if (data != null) {
        if (data.error == "0") {
          _paymentModes = data.paymentModes!;
          _paymentAccounts = data.paymentAccounts!;
          _paymentRequestDetails = data.paymentRequestDetails!;
          notifyListeners();
        }
      }
    } catch (e, s) {}
  }

  String? remarksError;
  String? ApprovedAmountError;

  Future<void> paymentrequisitionRejectSubmitAPIFunction(context,
      mode,
      payment_request_id,
      approve_remarks,) async {
    try {
      if(approve_remarks.toString().trim().isEmpty) {
        remarksError = "Please Enter Remarks";
        notifyListeners();
        // toast(context,"Enter Remarks");
        return;
      }
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.RejectPaymentRequestSubmitAPI(
        provider.empId,
        provider.session,
        mode,
        payment_request_id,
        approve_remarks,
      );
      if (data != null) {
        if (data.error == "0") {
          paymentRequesitionDetails(context, payment_request_id);
          resetAll();
          toast(context, data.message);
          Navigator.pop(context);
        }
      }
    } catch (e, s) {}
  }

  Future<void> paymentrequisitionApproveSubmitAPIFunction(context,
      mode,
      payment_request_id,
      approved_amount,
      approve_remarks,
      proposed_payment_account_id,) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.ApprovePaymentRequestSubmitAPI(
        provider.empId,
        provider.session,
        mode,
        payment_request_id,
        approved_amount,
        approve_remarks,
        proposed_payment_account_id,
      );
      if(approved_amount.toString().trim().isEmpty){
        ApprovedAmountError = "Enter Amount";
        notifyListeners();
        return;
      }
      if(approve_remarks.toString().trim().isEmpty) {
        remarksError = "Please Enter Remarks";
        notifyListeners();
        return;
      }
      if (data != null) {
        if (data.error == "0") {
          paymentRequesitionDetails(context, payment_request_id);
          resetAll();
          toast(context, data.message);
          Navigator.pop(context,true);
          notifyListeners();
        }
      }
    } catch (e, s) {}
  }

  Future<void> paymentrequisitionProcessSubmitAPIFunction(context,
      mode,
      reference_num,
       payment_amount,
      payment_request_id,
      payment_account_id,
      processing_remarks,
      attachment,) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.processApproveRejectPaymentRequestSubmitAPI(
        provider.empId,
        provider.session,
        mode,
        reference_num,
        payment_amount,
        payment_request_id,
        payment_account_id,
        processing_remarks,
        attachment,
      );
      if (data != null) {
        if (data.error == "0") {
          paymentRequesitionDetails(context, payment_request_id);
          resetAll();
          toast(context, data.message);
          Navigator.pop(context);
        }
      }
    } catch (e, s) {}
  }

  resetAll() {
    requestedAmount.clear();
    proposedPaymentAccount.clear();
    approvedAmountReadonly.clear();
    approvedAmount.clear();
    accountName.clear();
    branch.clear();
    requestingPurpose.clear();
    description.clear();
    amount.clear();
    paymentMode.clear();
    bankUpiID.clear();
    bankName.clear();
    bankBranchName.clear();
    bankAccountNumber.clear();
    bankIfscCode.clear();
    bankHolderName.clear();
    paymentAccountSearchController.clear();
    _selectedPaymentAccounts = null;
    _selectedValue = "";
    _selectedID = null;
    proposedAmountError = null;
    remarksError = null;
    ApprovedAmountError = null;
    checkDropDownReset();
    notifyListeners();

  }

  void checkDropDownReset() {
    if (!_paymentAccounts.contains(_selectedPaymentAccounts) &&
        _selectedPaymentAccounts != null) {
      _selectedPaymentAccounts = null;
      _selectedID = null;
      _selectedValue ="";
    }
    notifyListeners();
  }
}
