import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

import '../../Models/ordersModels/orderDashboardResponse.dart';
import '../../Models/ordersModels/ordersAccessiblePagesResponse.dart';
import '../../Models/ordersModels/ordersDetailsByModeResponse.dart';
import '../../Models/ordersModels/ordersListByModeFilterResponse.dart';
import '../../Models/ordersModels/ordersListByModeResponse.dart';
import '../../Utils/commonServices.dart';
import '../../services/api_calling.dart';
import '../HomeScreenNotifier.dart';

class Pagesdashboardprovider extends ChangeNotifier {
  bool _submitClicked = false;
  bool _showMoreDetails = false;

  TextEditingController feedbackController = TextEditingController();
  TextEditingController approveRejectFeedbackController =
      TextEditingController();
  TextEditingController saleOrderNumberController = TextEditingController();
  TextEditingController deleteFeedbackController = TextEditingController();
  TextEditingController editCompanyController = TextEditingController();
  TextEditingController otpController = TextEditingController();
  String _enteredOTP = "";
  String? feedbackError;
  String? deleteFeedbackError;
  String? approveRejectFeedbackError;
  String? saleOrderNumberError;
  String? companyNameError;
  List<PagesAccessible> _ordersAccessiblePagesList = [];
  List<PagesAccessible> _ordersAccessiblePagesList2 = [];
  List<Employees> _employeesList = [];
  List<String> _leadStatus = [];
  List<OrderList> _ordersList = [];
  List<Products> _productsHistory = [];
  List<FeedbackHistory> _feedbackHistory = [];
  List<PaymentHistory> _paymentHistory = [];
  bool _isLoading = true;
  Employees? _selectedEmployee;
  String? _selectedLeadType;
  String? _selectedEmpID;
  String? _selectedEmpName;
  OrderDetails _orderDetails = OrderDetails();
  List<String> _headings = [];
  List<String> _subHeadings = [];
  String _approvalSheetHeading = "";
  String _rejecetionSheetHeading = "";
  String _deletionSheetHeading = "";
  var _image_picked = 0;
  final ImagePicker _picker = ImagePicker();

  Ordergain _ordergain = Ordergain();
  Ordergain get ordergain => _ordergain;
  Ordergain _dispatches = Ordergain();
  Ordergain get dispatches => _dispatches;
  Ordergain _pendingTasks = Ordergain();
  Ordergain get pendingTasks => _pendingTasks;
  Ordergain _quote = Ordergain();
  Ordergain get quote => _quote;
  List<Ordergain> _ordersgain = [];
  List<Ordergain> get ordersgain => _ordersgain;
  bool get showMoreDetails => _showMoreDetails;
  set showMoreDetails(bool value) {
    _showMoreDetails = value;
    notifyListeners();
  }

  File? _image;
  File? _imageName;

  String get enteredOtp => _enteredOTP;

  bool get submitClicked => _submitClicked;

  set submitClicked(bool value) {
    _submitClicked = value;
    notifyListeners();
  }

  String get approvalSheetHeading => _approvalSheetHeading;

  String get rejecetionSheetHeading => _rejecetionSheetHeading;

  String get deletionSheetHeading => _deletionSheetHeading;

  set enteredOtp(String value) {
    _enteredOTP = value;
    notifyListeners();
  }

  set approvalSheetHeading(String value) {
    _approvalSheetHeading = value;
    notifyListeners();
  }

  set rejecetionSheetHeading(String value) {
    _rejecetionSheetHeading = value;
    notifyListeners();
  }

  set deletionSheetHeading(String value) {
    _deletionSheetHeading = value;
    notifyListeners();
  }

  get image_picked => _image_picked;

  File? get imagePath => _imageName;

  File? get imageFilePath => _image;

  get imagePicked => _image_picked;

  List<PagesAccessible> get ordersAccessiblePagesList =>
      _ordersAccessiblePagesList;

  List<PagesAccessible> get ordersAccessiblePagesList2 =>
      _ordersAccessiblePagesList2;

  List<Employees> get employeesList => _employeesList;

  List<OrderList> get ordersList => _ordersList;

  OrderDetails get orderDetails => _orderDetails;

  List<Products> get productsHistory => _productsHistory;

  List<FeedbackHistory> get feedbackHistory => _feedbackHistory;

  List<PaymentHistory> get paymentHistory => _paymentHistory;

  List<String> get leadStatus => _leadStatus;

  bool get isLoading => _isLoading;

  Employees? get selectedEmployee => _selectedEmployee;

  String? get selectedEmpID => _selectedEmpID;

  String? get selectedEmpName => _selectedEmpName;

  String? get selectedLeadType => _selectedLeadType;

  // List<String> get Headings => _headings;
  //
  // List<String> get subHeadings => _subHeadings;

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

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

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

  set selectedLeadType(String? value) {
    _selectedLeadType = 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();
  }

  void resetAll() {
    feedbackController.clear();
    approveRejectFeedbackController.clear();
    editCompanyController.clear();
    saleOrderNumberController.clear();
    deleteFeedbackController.clear();
    saleOrderNumberError = "";
    companyNameError = "";
    deleteFeedbackError = "";
    approveRejectFeedbackError = "";
    _image = null;
    _imageName = null;
    _image_picked = 0;
    _selectedEmployee = null;
    _selectedEmpID = "";
    _selectedEmpName = "";
    _selectedLeadType = "";

    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;
      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;
      notifyListeners();
      // var file = FlutterImageCompress.compressWithFile(galleryImage!.path);
    } catch (e) {
      debugPrint("mmmm: ${e.toString()}");
    }
  }

  Future<void> orderDashboardAPIFunction(
    context,
    mode,
    from,
    to,
    teamemployee,
  ) async {
    try {
      var HomeProv = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.ordersDashboardAPI(
        HomeProv.empId,
        HomeProv.session,
        mode,
        from,
        to,
        teamemployee,
      );
      if (data != null) {
        if (data.error == "0") {
          _ordergain = data.ordergain!;
          _dispatches = data.dispatches!;
          _pendingTasks = data.pendingTasks!;
          _quote = data.quote!;
          _ordersgain = [_ordergain, _dispatches, _pendingTasks, _quote];
          notifyListeners();
        }
      }
    } catch (e) {}
  }

  Future<void> ordersAccessiblePagesAPIFunction(context) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.ordersAccesiblePagesAPI(
        provider.empId,
        provider.session,
      );
      if (data != null) {
        if (data.error == "0") {
          _ordersAccessiblePagesList = data.pagesAccessible!;
          print(data.pagesAccessible!.map((e) => e.pageName));
          notifyListeners();
        } else {}
      }
    } catch (e) {}
  }

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

  Future<void> ordersListByModeFilterAPIFunction(context, mode) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.ordersListByModeFilterAPI(
        provider.empId,
        provider.session,
        mode,
      );
      if (data != null) {
        if (data.error == "0") {
          _employeesList = data.employees!;
          _leadStatus = data.leadStatus!;
          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;

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

  Future<void> ordersListByModeAPIFunction(
    BuildContext context,
    String mode,
    String teamEmployee,
    String status, {
    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.ordersListByModeAPI(
        provider.empId,
        provider.session,
        mode,
        teamEmployee,
        status,
        _currentPage.toString(),
      );
      debugPrint(
        'empId: ${provider.empId}, session: ${provider.session}, pageNumber: $_currentPage',
      );

      if (data != null && data.error == "0") {
        if (append) {
          _ordersList.addAll(data.orderList ?? []);
        } else {
          _ordersList = data.orderList ?? [];
          if (_selectedEmployee != null &&
              !_employeesList.contains(_selectedEmployee)) {
            _selectedEmployee = null;
            _selectedEmpID = "";
            _selectedEmpName = "";
          }
        }

        if (data.orderList == null || data.orderList!.length < 10) {
          _hasMoreData = false;
        }
      } else {
        if (!append) _errorMessage = "No orders found!";
        _hasMoreData = false;
      }
    } catch (e) {
      _errorMessage = "Error: $e";
    }
    if (_selectedEmployee != null &&
        !_employeesList.contains(_selectedEmployee)) {
      _selectedEmployee = null;
      _selectedEmpID = "";
      _selectedEmpName = "";
    }

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

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

  Future<void> ordersDetailsByModeAPIFunction(context, orderId, mode) async {
    try {
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.ordersDetailsByModeAPI(
        provider.empId,
        provider.session,
        orderId,
      );
      if (data != null) {
        // _isLoading = true;
        notifyListeners();
        if (data.error == "0") {
          _orderDetails =
              data.orderDetails ??
              OrderDetails(
                id: "",
                orderNumber: "",
                orderNumberHash: "",
                balanceAmount: "",
                accId: "",
                refType: "",
                refId: "",
                salesPersonEmpId: "",
                enteredEmpId: "",
                dispatchStateId: "",
                dispatchDistrictId: "",
                dispatchSubLocationId: "",
                dispatchPincode: "",
                dispatchAddress: "",
                basicAmount: "",
                cgstAmount: "",
                sgstAmount: "",
                igstAmount: "",
                paidAmount: "",
                totalAmount: "",
                status: "",
                orderReceivedDate: "",
                scheduledDispatchDate: "",
                otp: "",
                note: "",
                poViewFileName: "",
                poDirFilePath: "",
                unloadingScope: "",
                freightScope: "",
                erectionScope: "",
                saleOrderNumber: "",
                invoiceNumber: "",
                vehicleNumber: "",
                driverName: "",
                driverMobileNumber: "",
                tpcApplicable: "",
                requestedTpcAmount: "",
                level1TpcApprovedAmount: "",
                level2TpcApprovedAmount: "",
                tpcPaymentMode: "",
                tpcPaymentReferenceNo: "",
                tpcPaymentAttachmentDirFilePath: "",
                tpcPaymentAttachementViewFileName: "",
                tpcStatus: "",
                tpcAgentId: "",
                isExist: "",
                createdDatetime: "",
                updatedDatetime: "",
                accountName: "",
                gstNumber: "",
                billingAddress: "",
                billingDistrict: "",
                billingState: "",
                billingSubLocality: "",
                billingPincode: "",
                stateName: "",
                districtName: "",
                subLocationName: "",
                adjustedAmount: "",
                enteredEmpName: "",
                salesPersonEmpName: "",
                tpcaAgentName: "",
              );
          _productsHistory = data.products!;
          _feedbackHistory = data.feedbackHistory!;
          _paymentHistory = data.paymentHistory!;
          editCompanyController.text = data.orderDetails!.accountName ?? "";
          _headings = [
            "Order Number",
            "Account Name",

            "Billing State",
            "Billing District",
            "Billing Sub Location",
            "Billing Pincode",
            "Billing Address",

            "Sales Person Name",
            "Entered By",

            "Dispatch State",
            "Dispatch District",
            "District Sub Location",
            "Dispatch Pincode",
            "Dispatch Address",

            "GST Number",

            "Unloading Scope",
            "Freight Scope",
            "Erection Scope",
            "Order Received Date",

            "CGST Amount",
            "SGST Amount",
            "IGST Amount",

            "OTP",

            "Basic Amount",
            "Paid Amount",
            "Balance Amount",
            "Total Amount",

            "TPC Applicable",
            "TPC Agent",
            "TPC Requested Amount",

            "TPC Level 1 Approved Amount",
            "TPC Level 2 Approved Amount",

            "TPC Payment Mode",
            "TPC Payment Reference No",
            "TPC Payment Attachment",
            "TPC Status",
            "Purchase Order",

            "Created Datetime",
            "Note",
            "Status",
          ];
          _subHeadings = [
            _orderDetails.orderNumber ?? "-",
            _orderDetails.accountName ?? "-",

            _orderDetails.billingState ?? "-",
            _orderDetails.billingDistrict ?? "-",
            _orderDetails.billingSubLocality ?? "-",
            _orderDetails.billingPincode ?? "-",
            _orderDetails.billingAddress ?? "-",

            _orderDetails.salesPersonEmpName ?? "-",
            _orderDetails.enteredEmpName ?? "-",

            _orderDetails.stateName ?? "-",
            _orderDetails.districtName ?? "-",
            _orderDetails.subLocationName ?? "-",
            _orderDetails.dispatchPincode ?? "-",
            _orderDetails.dispatchAddress ?? "-",

            _orderDetails.gstNumber ?? "-",

            _orderDetails.unloadingScope ?? "-",
            _orderDetails.freightScope ?? "-",
            _orderDetails.erectionScope ?? "-",
            _orderDetails.orderReceivedDate ?? "-",

            _orderDetails.cgstAmount ?? "-",
            _orderDetails.sgstAmount ?? "-",
            _orderDetails.igstAmount ?? "-",

            _orderDetails.otp ?? "-",

            _orderDetails.basicAmount ?? "-",
            _orderDetails.paidAmount ?? "-",
            _orderDetails.balanceAmount ?? "-",
            _orderDetails.totalAmount ?? "-",

            _orderDetails.tpcApplicable ?? "-",
            _orderDetails.tpcaAgentName ?? "-",
            _orderDetails.requestedTpcAmount ?? "-",

            _orderDetails.level1TpcApprovedAmount ?? "-",
            _orderDetails.level2TpcApprovedAmount ?? "-",

            _orderDetails.tpcPaymentMode ?? "-",
            _orderDetails.tpcPaymentReferenceNo ?? "-",
            _orderDetails.tpcPaymentAttachementViewFileName ?? "-",
            _orderDetails.tpcStatus ?? "-",
            _orderDetails.tpcPaymentAttachmentDirFilePath ?? "-",

            _orderDetails.createdDatetime ?? "-",
            _orderDetails.note ?? "-",
            _orderDetails.status ?? "-",
          ];
          _isLoading = false;
          switch (mode) {
            case "admin":
              approvalSheetHeading = "";
              rejecetionSheetHeading = "";
              deletionSheetHeading = "Delete order";
              break;
            case "level_one_approval":
              approvalSheetHeading = "Level 1 Approval";
              rejecetionSheetHeading = "Level 1 Reject";
              deletionSheetHeading = "";
              break;
            case "level_two_approval":
              approvalSheetHeading = "Level 2 Approval";
              rejecetionSheetHeading = "Level 2 Reject";
              deletionSheetHeading = "";
              break;
            case "level_two_rejected":
              approvalSheetHeading = "Level 2 Approval Update";
              rejecetionSheetHeading = "Level 2 Final Reject";
              deletionSheetHeading = "";
              break;
            case "sales_order_registered":
              approvalSheetHeading = "Sales Order Registered";
              rejecetionSheetHeading = "";
              deletionSheetHeading = "";
              break;
            case "dispatched":
              approvalSheetHeading = "";
              rejecetionSheetHeading = "";
              deletionSheetHeading = "";
              break;
            default:
              approvalSheetHeading = "";
              rejecetionSheetHeading = "";
              deletionSheetHeading = "";
              break;
          }
        } else {
          _isLoading = false;
        }
        notifyListeners();
      }
    } catch (e) {}
  }

  Future<void> ordersDetailsFeedbackSubmissionAPIFunction(
    context,
    orderId,
    status,
  ) async {
    try {
      if (!validateFeedbackForm(context)) {
        // _submitClicked = false;
        return;
      }
      _submitClicked = true;
      notifyListeners();
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.ordersDetailsFeedbackSubmissionAPI(
        provider.empId,
        provider.session,
        orderId,
        feedbackController.text,
        status,
        _image,
      );
      if (data != null) {
        if (data.error == "0") {
          _submitClicked = false;
          toast(context, "Submitted Successfully");
          resetForm();
          Navigator.pop(context, true);
          notifyListeners();
        } else {
          _submitClicked = false;
          notifyListeners();
        }
      } else {
        _submitClicked = false;
        notifyListeners();
      }
    } catch (e) {
      _submitClicked = false;
      notifyListeners();
    }
  }

  Future<void> approvalRejectionAPIFunction(
    context,
    status,
    orderId,
    type,
    tpcApplicable,
    tpcApprovedAmount,
    invoiceNumber,
    vehicleNumber,
    driverName,
    driverMobileNo,
    crmOrderPId,
    mode,
  ) async {
    try {
      if (!validateApproveRejectForm(context, mode)) {
        // _submitClicked = false;
        return;
      }
      _submitClicked = true;
      notifyListeners();
      var provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.ordersDetailsApproveRejectAPI(
        provider.empId,
        provider.session,
        status,
        type,
        orderId,
        approveRejectFeedbackController.text,
        tpcApplicable,
        tpcApprovedAmount,
        saleOrderNumberController.text,
        editCompanyController.text,
        invoiceNumber,
        vehicleNumber,
        driverName,
        driverMobileNo,
        crmOrderPId,
      );
      if (data != null) {
        if (data.error == "0") {
          _submitClicked = false;
          toast(context, "${data.message}");
          resetForm();
          Navigator.pop(context, true);
          notifyListeners();
        } else {}
      }
    } catch (e) {}
  }

  Future<void> delectionAPIFunction(context, orderId) async {
    try {
      if (!validateDeleteForm(context)) {
        // _submitClicked = false;
        return;
      }
      final provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.ordersDetailsDeleteAPI(
        provider.empId,
        provider.session,
        orderId,
        deleteFeedbackController.text,
      );
      if (data != null) {
        if (data.error == "0") {
          toast(context, "${data.message}");
          resetForm();
          Navigator.pop(context, true);
          notifyListeners();
        } else {
          _submitClicked = false;
          notifyListeners();
        }
      } else {
        _submitClicked = false;
        notifyListeners();
      }
    } catch (e) {
      _submitClicked = false;
      notifyListeners();
    }
  }

  Future<void> verifyOrderAPIFunction(context, orderId, otp) async {
    try {
      if (otp.isEmpty) {
        toast(context, "Please Enter OTP");
        _submitClicked = false;
        return;
      }
      final provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final data = await ApiCalling.verifyOrderAPI(
        provider.empId,
        provider.session,
        orderId,
        otp,
      );
      if (data != null) {
        if (data.error == "0") {
          toast(context, "${data.message}");
          // otpController.clear();
          Navigator.pop(context, true);
          notifyListeners();
        } else {
          toast(context, data.message!);
          _submitClicked = false;
          notifyListeners();
        }
      } else {
        _submitClicked = false;
        notifyListeners();
      }
    } catch (e) {
      _submitClicked = false;
      notifyListeners();
    }
  }

  Future<void> ResendOtpAPI(context, orderId) async {
    try {
      var homeProvider = Provider.of<HomescreenNotifier>(
        context,
        listen: false,
      );
      final data = await ApiCalling.resendOTPOrderAPI(
        homeProvider.empId,
        homeProvider.session,
        orderId,
      );

      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            toast(context, data.message);
          } else {
            toast(context, data.message);
          }
        } else {}
      } else {}
    } on Error catch (e) {
      debugPrint(e.toString());
    }
  }

  void onChangeFeedback(value) {
    feedbackError = "";
    notifyListeners();
  }

  void onChangeDeletion(value) {
    deleteFeedbackError = "";
    notifyListeners();
  }

  void onChangeApproveRejection(value) {
    approveRejectFeedbackError = "";
    notifyListeners();
  }

  void onChangeSaleOrderNumber(value) {
    saleOrderNumberError = "";
    notifyListeners();
  }

  void onChangeEditCompanyName(value) {
    companyNameError = "";
    notifyListeners();
  }

  bool validateFeedbackForm(BuildContext context) {
    // Reset all errors
    feedbackError = null;

    bool isValid = true;

    if (feedbackController.text.trim().isEmpty) {
      feedbackError = "Please enter a description";
      isValid = false;
    }

    //
    // buttonEnabled = isValid;
    notifyListeners();
    return isValid;
  }

  bool validateDeleteForm(BuildContext context) {
    // Reset all errors
    deleteFeedbackError = null;

    bool isValid = true;

    if (deleteFeedbackController.text.trim().isEmpty) {
      deleteFeedbackError = "Please enter a description";
      isValid = false;
    }

    //
    // buttonEnabled = isValid;
    notifyListeners();
    return isValid;
  }

  bool validateApproveRejectForm(BuildContext context, mode) {
    // Reset all errors
    approveRejectFeedbackError = null;
    companyNameError = null;
    saleOrderNumberError = null;

    bool isValid = true;

    if (approveRejectFeedbackController.text.trim().isEmpty) {
      approveRejectFeedbackError = "Please enter a description";
      isValid = false;
    }
    if (mode == "dispatched") {
      if (editCompanyController.text.trim().isEmpty) {
        companyNameError = "Please enter a description";
        isValid = false;
      }
      if (saleOrderNumberController.text.trim().isEmpty) {
        saleOrderNumberError = "Please enter a description";
        isValid = false;
      }
    }

    //
    // buttonEnabled = isValid;
    notifyListeners();
    return isValid;
  }

  void resetForm() {
    otpController.clear();
    feedbackController.clear();
    approveRejectFeedbackController.clear();
    editCompanyController.clear();
    saleOrderNumberController.clear();
    deleteFeedbackController.clear();
    saleOrderNumberError = "";
    companyNameError = "";
    deleteFeedbackError = "";
    approveRejectFeedbackError = "";
    _image = null;
    _imageName = null;
    _image_picked = 0;
  }

  // List<List<String>> prepareExportData() {
  //   final headers = [
  //     'ID',
  //     'Payment Account',
  //     'Amount',
  //     'Branch',
  //     'Account Number',
  //     'Description',
  //     'Mode',
  //     'Payment Reference Number',
  //     'Created Employee',
  //     'Date',
  //   ];
  //
  //   final rows =
  //   ordersList
  //       .map(
  //         (item) =>
  //     [
  //       item.id ?? '',
  //       item.payAccount ?? '',
  //       item.amount ?? '',
  //       item.bankName??"",
  //       item.bankBranchName ?? '',
  //       item.bankAccountNumber ?? '',
  //       item.description ?? '',
  //       item.requestMode ?? '',
  //       item.paymentReferenceNumber ?? '',
  //       item.createdEmployee ?? '',
  //       item.createdDatetime ?? '',
  //     ],
  //   )
  //       .toList();
  //
  //   return [headers, ...rows];
  // }
  //
  // void copyToClipboard(BuildContext context) async {
  //   try {
  //     if (paymentsList.isEmpty) {
  //       ScaffoldMessenger.of(
  //         context,
  //       ).showSnackBar(SnackBar(content: Text("No data to copy")));
  //       return;
  //     }
  //     final data = prepareExportData();
  //     String raw = data.map((row) => row.join('\t')).join('\n');
  //     print('Clipboard data: $raw');
  //     await Clipboard.setData(ClipboardData(text: raw));
  //     toast(context, "Copied to Clipboard");
  //   } catch (e) {
  //     print('Error copying to clipboard: $e');
  //   }
  // }
  //
  // Future<String> getSaveDirectory() async {
  //   // Try Downloads directory first
  //   try {
  //     if (Platform.isAndroid) {
  //       // Request storage permission for Android
  //       if (await Permission.storage
  //           .request()
  //           .isGranted ||
  //           await Permission.manageExternalStorage
  //               .request()
  //               .isGranted) {
  //         final dir = await getApplicationDocumentsDirectory();
  //         if (dir != null) {
  //           print('Using Downloads directory: ${dir.path}');
  //           return dir.path;
  //         }
  //       }
  //     }
  //   } catch (e) {
  //     print('Error accessing Downloads directory: $e');
  //   }
  //
  //   // Fallback to shared Documents directory
  //   try {
  //     final dir = await getDownloadsDirectory();
  //     if (dir != null) {
  //       final customDir = Directory('${dir.path}/RequisitionData');
  //       if (!await customDir.exists()) {
  //         await customDir.create(recursive: true);
  //       }
  //       print('Using custom Documents directory: ${customDir.path}');
  //       return customDir.path;
  //     }
  //   } catch (e) {
  //     print('Error accessing Documents directory: $e');
  //   }
  //
  //   // Final fallback to app's Documents directory
  //   final dir = await getApplicationDocumentsDirectory();
  //   print('Using app Documents directory: ${dir.path}');
  //   return dir.path;
  // }
  //
  // Future<void> downloadCSV(BuildContext context) async {
  //   try {
  //     if (paymentsList.isEmpty) {
  //       ScaffoldMessenger.of(
  //         context,
  //       ).showSnackBar(SnackBar(content: Text("No data to export")));
  //       return;
  //     }
  //     final data = prepareExportData();
  //     final csvData = const ListToCsvConverter().convert(data);
  //     final dirPath = await getSaveDirectory();
  //     final file = File('$dirPath/requisition_data.csv');
  //     await file.writeAsString(csvData);
  //     print('CSV saved at: ${file.path}');
  //     bool exists = await file.exists();
  //     print('File exists: $exists');
  //     // await OpenFile.open(file.path); // Open the file
  //     // await Share.share(file.path); // Share the file
  //     toast(context, "CSV Downloaded");
  //   } catch (e) {
  //     print('Error downloading CSV: $e');
  //   }
  // }
  //
  // Future<void> downloadXLS(BuildContext context) async {
  //   try {
  //     if (paymentsList.isEmpty) {
  //       toast(context, "No Data to export");
  //       return;
  //     }
  //     final data = prepareExportData();
  //     var excel = Excel.createExcel();
  //     Sheet sheet = excel['Sheet1'];
  //     for (var row in data) {
  //       sheet.appendRow(row.map((cell) => TextCellValue(cell)).toList());
  //     }
  //     final dirPath = await getSaveDirectory();
  //     final file = File('$dirPath/requisition_data.xlsx');
  //     final bytes = excel.encode();
  //     if (bytes == null) throw Exception("Excel encoding failed");
  //     await file.writeAsBytes(bytes);
  //     print('XLSX saved at: ${file.path}');
  //     bool exists = await file.exists();
  //     print('File exists: $exists');
  //     // await OpenFile.open(file.path); // Open the file
  //     // await Share.share([file.path], text: 'Requisition Data XLSX'); // Share the file
  //     toast(context, ("XLSX Downloaded and opened"));
  //   } catch (e) {
  //     print('Error downloading XLSX: $e');
  //   }
  // }
  //
  // Future<void> downloadPDF(BuildContext context) async {
  //   try {
  //     if (paymentsList.isEmpty) {
  //       toast(context, "No Data to export");
  //       return;
  //     }
  //     final data = prepareExportData();
  //     final pdf = pw.Document();
  //     pdf.addPage(
  //       pw.Page(build: (context) => pw.Table.fromTextArray(data: data)),
  //     );
  //     final dirPath = await getSaveDirectory();
  //     final file = File('$dirPath/requisition_data.pdf');
  //     await file.writeAsBytes(await pdf.save());
  //     print('PDF saved at: ${file.path}');
  //     bool exists = await file.exists();
  //     print('File exists: $exists');
  //     // await OpenFile.open(file.path); // Open the file
  //     // await Share.shareXFiles([file.path], text: 'Requisition Data PDF'); // Share the file
  //     toast(context, "PDF Downloaded ");
  //   } catch (e) {
  //     print('Error downloading PDF: $e');
  //   }
  // }
  //
  // Future<void> printData(BuildContext context) async {
  //   try {
  //     if (paymentsList.isEmpty) {
  //       toast(context, "No Data to Print");
  //       return;
  //     }
  //     final data = prepareExportData();
  //     final pdf = pw.Document();
  //     pdf.addPage(
  //       pw.Page(build: (context) => pw.Table.fromTextArray(data: data)),
  //     );
  //     await Printing.layoutPdf(
  //       onLayout: (PdfPageFormat format) async => pdf.save(),
  //     );
  //   } catch (e) {
  //     print('Error printing data: $e');
  //   }
  // }
}
