import 'dart:async';

import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:hugeicons/hugeicons.dart';
import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:provider/provider.dart' as pro;
import 'package:responsive_grid/responsive_grid.dart';
import 'package:salespro_admin/Screen/Home/total_count_widget.dart';
import 'package:salespro_admin/Screen/Sale%20List/show_edit_payment_popup.dart';
import 'package:salespro_admin/Screen/Widgets/Constant%20Data/constant.dart';
import 'package:salespro_admin/generated/l10n.dart' as lang;

import '../../PDF/print_pdf.dart';
import '../../Provider/customer_provider.dart';
import '../../Provider/product_provider.dart';
import '../../Provider/profile_provider.dart';
import '../../commas.dart';
import '../../const.dart';
import '../../currency.dart';
import '../../model/add_to_cart_model.dart';
import '../../model/category_model.dart';
import '../../model/customer_model.dart';
import '../../model/personal_information_model.dart';
import '../../model/product_model.dart';
import '../../model/sale_transaction_model.dart';
import '../../subscription.dart';
import '../Product/WarebasedProduct.dart';
import '../WareHouse/warehouse_model.dart';
import '../Widgets/Calculator/calculator.dart';
import '../currency/currency_provider.dart';

class EditPosSale extends ConsumerStatefulWidget {
  const EditPosSale({
    super.key,
    required this.transitionModel,
    required this.personalInformationModel,
    required this.isPosScreen,
    required this.popUpContext,
  });

  final SaleTransactionModel transitionModel;
  final PersonalInformationModel personalInformationModel;
  final bool isPosScreen;
  final BuildContext popUpContext;

  @override
  ConsumerState<EditPosSale> createState() => _EditPosSaleState();
}

class _EditPosSaleState extends ConsumerState<EditPosSale> {
  List<AddToCartModel> cartList = [];
  List<FocusNode> productFocusNode = [];
  String searchProductCode = '';
  Map<int, bool> _tappedStates = {};
  String isSelected = 'Categories';
  String selectedCategory = 'Categories';

  CustomerModel selectedUserName = CustomerModel(
    customerName: "Guest",
    phoneNumber: "",
    type: "Guest",
    customerAddress: '',
    emailAddress: '',
    profilePicture: '',
    openingBalance: 0,
    remainedBalance: 0,
    dueAmount: 0,
    gst: '',
    receiveWhatsappUpdates: false,
  );

  String? invoiceNumber;
  String previousDue = "0";
  FocusNode nameFocus = FocusNode();
  String? selectedUserId;

  List<String> customerType = ['Retailer', 'Wholesaler', 'Dealer'];
  String selectedCustomerType = 'Retailer';

  DateTime selectedDueDate = DateTime.now();
  double serviceCharge = 0;
  double discountAmount = 0;

  TextEditingController discountAmountEditingController = TextEditingController();
  TextEditingController discountPercentageEditingController = TextEditingController();
  TextEditingController vatPercentageEditingController = TextEditingController();
  TextEditingController nameCodeCategoryController = TextEditingController();

  final ScrollController mainSideScroller = ScrollController();
  WareHouseModel? selectedWareHouse;
  int i = 0;
  final _horizontalScroll = ScrollController();

  List<AddToCartModel> pastProducts = [];
  List<AddToCartModel> decreaseStockList = [];

  @override
  void initState() {
    super.initState();
    checkCurrentUserAndRestartApp();
    checkInternet();

    // Initialize with the transaction model data
    cartList = widget.transitionModel.productList ?? [];
    selectedCustomerType = widget.transitionModel.customerType ?? 'Retailer';
    discountAmount = widget.transitionModel.discountAmount ?? 0;
    serviceCharge = widget.transitionModel.serviceCharge ?? 0;
    discountAmountEditingController.text = discountAmount.toStringAsFixed(2);

    selectedUserName = CustomerModel(
      customerName: widget.transitionModel.customerName,
      phoneNumber: widget.transitionModel.customerPhone,
      type: widget.transitionModel.customerType,
      customerAddress: widget.transitionModel.customerAddress,
      emailAddress: '',
      profilePicture: widget.transitionModel.customerImage,
      openingBalance: 0,
      remainedBalance: 0,
      dueAmount: 0,
      gst: widget.transitionModel.customerGst,
      receiveWhatsappUpdates: widget.transitionModel.sendWhatsappMessage ?? false,
    );

    selectedUserId = widget.transitionModel.customerPhone;
    previousDue = "0"; // You may need to fetch this from customer data

    // Initialize focus nodes
    for (var _ in cartList) {
      addFocus();
    }
  }

  @override
  void dispose() {
    nameCodeCategoryController.dispose();
    discountAmountEditingController.dispose();
    discountPercentageEditingController.dispose();
    vatPercentageEditingController.dispose();
    nameFocus.dispose();
    for (var focusNode in productFocusNode) {
      focusNode.dispose();
    }
    super.dispose();
  }

  void addFocus() {
    FocusNode f = FocusNode();
    f.addListener(() {
      if (!f.hasFocus) {
        setState(() {});
      }
    });
    productFocusNode.add(f);
  }

  dynamic productPriceChecker({required ProductModel product, required String customerType}) {
    if (customerType == "Retailer") {
      return product.productSalePrice;
    } else if (customerType == "Wholesaler") {
      return product.productWholeSalePrice == '' ? '0' : product.productWholeSalePrice;
    } else if (customerType == "Dealer") {
      return product.productDealerPrice == '' ? '0' : product.productDealerPrice;
    } else if (customerType == "Guest") {
      return product.productSalePrice;
    }
  }

  String getTotalAmount() {
    double total = 0.0;
    for (var item in cartList) {
      total = total + (double.parse(item.subTotal) * item.quantity);
    }
    return total.toStringAsFixed(2);
  }

  bool uniqueCheck(String code) {
    bool isUnique = false;
    for (var item in cartList) {
      if (item.productId == code) {
        if (item.quantity < item.stock!) {
          item.quantity += 1;
        } else {
          EasyLoading.showError('Out of Stock');
        }
        isUnique = true;
        break;
      }
    }
    return isUnique;
  }

  bool uniqueCheckForSerial({required String code, required List<dynamic> newSerialNumbers}) {
    bool isUnique = false;
    for (var item in cartList) {
      if (item.productId == code) {
        item.serialNumber = newSerialNumbers;
        item.quantity = newSerialNumbers.isEmpty ? 1 : newSerialNumbers.length;
        isUnique = true;
        break;
      }
    }
    return isUnique;
  }

  Future<void> _selectedDueDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(context: context, initialDate: selectedDueDate, firstDate: DateTime(2015, 8), lastDate: DateTime(2101));
    if (picked != null && picked != selectedDueDate) {
      setState(() {
        selectedDueDate = picked;
      });
    }
  }

  LayoutBuilder getResult(List<CustomerModel> model, String currency) {
    List<DropdownMenuItem<String>> dropDownItems = [];
    for (var des in model) {
      var item = DropdownMenuItem(
        value: des.phoneNumber,
        child: FittedBox(
          fit: BoxFit.scaleDown,
          child: Text.rich(
            TextSpan(text: '${des.customerName} ${des.phoneNumber} ', children: [
              TextSpan(
                text: '$currency${myFormat.format(des.dueAmount)}',
                style: TextStyle(color: Colors.red),
              )
            ]),
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
                  color: kNeutral600,
                ),
          ),
        ),
      );
      dropDownItems.add(item);
    }

    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        double responsiveWidth;
        if (constraints.maxWidth > 1240) {
          responsiveWidth = constraints.maxWidth * 0.95;
        } else if (constraints.maxWidth < 800) {
          responsiveWidth = 400;
        } else {
          responsiveWidth = 500;
        }

        return DropdownButton2<String>(
          iconStyleData: IconStyleData(
            icon: Icon(
              Icons.keyboard_arrow_down,
              color: kNeutral600,
            ),
          ),
          hint: Text('Select a customer'),
          dropdownStyleData: DropdownStyleData(
            maxHeight: 400,
            width: MediaQuery.of(context).size.width > 1600 ? constraints.maxWidth * 2.3 : constraints.maxWidth * 2.36,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5),
            ),
            offset: const Offset(0, -5),
            scrollbarTheme: ScrollbarThemeData(
              radius: const Radius.circular(40),
              thickness: WidgetStateProperty.all(6),
              thumbVisibility: WidgetStateProperty.all(true),
            ),
          ),
          buttonStyleData: ButtonStyleData(
            height: 40,
            width: double.infinity,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(5),
                bottomLeft: Radius.circular(5),
              ),
              border: Border(
                left: BorderSide(color: kNeutral300),
                bottom: BorderSide(color: kNeutral300),
                top: BorderSide(color: kNeutral300),
              ),
            ),
          ),
          menuItemStyleData: const MenuItemStyleData(
            overlayColor: WidgetStatePropertyAll(kMainColor100),
            height: 40,
            padding: EdgeInsets.symmetric(horizontal: 16),
          ),
          items: dropDownItems,
          isExpanded: true,
          selectedItemBuilder: (BuildContext context) {
            return model.map((item) {
              return Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  item.customerName,
                  style: Theme.of(context).textTheme.titleMedium,
                  textAlign: TextAlign.center,
                ),
              );
            }).toList();
          },
          value: dropDownItems.isEmpty ? null : selectedUserId,
          onChanged: dropDownItems.isEmpty
              ? null
              : (String? value) {
                  if (value == null) return;
                  setState(() {
                    selectedUserId = value;
                    for (var element in model) {
                      if (element.phoneNumber == selectedUserId) {
                        selectedUserName = element;
                        previousDue = element.dueAmount.toString();
                        if (selectedCustomerType != element.type) {
                          selectedCustomerType = element.type;
                          cartList.clear();
                          productFocusNode.clear();
                        }
                      }
                    }
                    invoiceNumber = '';
                  });
                },
        );
      },
    );
  }

  DropdownButton2<WareHouseModel> getWare({required List<WareHouseModel> list}) {
    List<DropdownMenuItem<WareHouseModel>> dropDownItems = [];
    for (var element in list) {
      dropDownItems.add(DropdownMenuItem(
        value: element,
        child: Text(
          element.warehouseName,
          style: Theme.of(context).textTheme.titleMedium?.copyWith(color: kNeutral600),
          overflow: TextOverflow.ellipsis,
        ),
      ));
      if (i == 0) {
        selectedWareHouse = element;
      }
      i++;
    }

    return DropdownButton2<WareHouseModel>(
      items: dropDownItems,
      iconStyleData: IconStyleData(
        icon: Icon(
          Icons.keyboard_arrow_down,
          color: kNeutral600,
        ),
      ),
      dropdownStyleData: DropdownStyleData(
        maxHeight: 400,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5),
        ),
        offset: const Offset(0, -5),
        scrollbarTheme: ScrollbarThemeData(
          radius: const Radius.circular(40),
          thickness: WidgetStateProperty.all(6),
          thumbVisibility: WidgetStateProperty.all(true),
        ),
      ),
      buttonStyleData: ButtonStyleData(
        height: 40,
        width: double.infinity,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5),
          border: Border.all(color: kNeutral300),
        ),
      ),
      menuItemStyleData: const MenuItemStyleData(
        overlayColor: WidgetStatePropertyAll(kMainColor100),
        height: 40,
        padding: EdgeInsets.symmetric(horizontal: 16),
      ),
      isExpanded: true,
      value: selectedWareHouse,
      onChanged: (WareHouseModel? value) {
        setState(() {
          selectedWareHouse = value;
        });
      },
    );
  }

  DropdownButton<String> getCategories() {
    List<DropdownMenuItem<String>> dropDownItems = [];
    for (String des in customerType) {
      var item = DropdownMenuItem(
        value: des,
        child: Text(
          des,
          style: kTextStyle.copyWith(overflow: TextOverflow.ellipsis, color: kTitleColor),
        ),
      );
      dropDownItems.add(item);
    }
    return DropdownButton(
      isExpanded: true,
      items: dropDownItems,
      value: selectedCustomerType,
      onChanged: (value) {
        setState(() {
          cartList.clear();
          selectedCustomerType = value!;
        });
      },
    );
  }

  void showSerialNumberPopUp({required ProductModel productModel}) {
    AddToCartModel productInCart = AddToCartModel(
        productPurchasePrice: 0,
        serialNumber: [],
        productImage: '',
        warehouseName: '',
        warehouseId: '',
        subTaxes: [],
        excTax: 0,
        groupTaxName: '',
        groupTaxRate: 0,
        incTax: 0,
        margin: 0,
        taxType: '');
    List<dynamic> selectedSerialNumbers = [];
    List<String> list = [];

    for (var element in cartList) {
      if (element.productId == productModel.productCode) {
        productInCart = element;
        break;
      }
    }
    selectedSerialNumbers = productInCart.serialNumber ?? [];

    for (var element in productModel.serialNumber) {
      if (!selectedSerialNumbers.contains(element)) {
        list.add(element);
      }
    }

    TextEditingController editingController = TextEditingController();
    String searchWord = '';

    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setState1) {
            return Dialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5.0),
              ),
              child: SizedBox(
                width: 500,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(top: 10.0, left: 10.0, right: 10.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text(
                            lang.S.of(context).selectSerialNumber,
                            style: kTextStyle.copyWith(color: kTitleColor, fontWeight: FontWeight.bold, fontSize: 20.0),
                          ),
                          const Spacer(),
                          const Icon(FeatherIcons.x, color: kTitleColor, size: 25.0).onTap(() => {finish(context)})
                        ],
                      ),
                    ),
                    const Divider(thickness: 1.0, color: kLitGreyColor),
                    const SizedBox(height: 10.0),
                    Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          AppTextField(
                            controller: editingController,
                            showCursor: true,
                            cursorColor: kTitleColor,
                            onChanged: (value) {
                              setState1(() {
                                searchWord = value;
                              });
                            },
                            onFieldSubmitted: (value) {
                              for (var element in list) {
                                if (value == element) {
                                  setState1(() {
                                    selectedSerialNumbers.add(element);
                                    editingController.clear();
                                    searchWord = '';
                                    list.removeWhere((element1) {
                                      return element1 == element;
                                    });
                                  });
                                  break;
                                }
                              }
                            },
                            textFieldType: TextFieldType.NAME,
                            suffix: const Icon(Icons.search),
                            decoration: kInputDecoration.copyWith(
                              border: const OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(30))),
                              labelText: lang.S.of(context).searchSerialNumber,
                              hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                              labelStyle: kTextStyle.copyWith(color: kTitleColor),
                            ),
                          ),
                          const SizedBox(height: 20),
                          Text(lang.S.of(context).serialNumber),
                          const SizedBox(height: 10.0),
                          Container(
                            height: MediaQuery.of(context).size.height / 4,
                            width: 500,
                            decoration: BoxDecoration(border: Border.all(width: 1, color: Colors.grey), borderRadius: const BorderRadius.all(Radius.circular(10))),
                            child: Padding(
                              padding: const EdgeInsets.all(10.0),
                              child: ListView.builder(
                                shrinkWrap: true,
                                itemCount: list.length,
                                itemBuilder: (BuildContext context, int index) {
                                  return Padding(
                                    padding: const EdgeInsets.only(bottom: 10),
                                    child: GestureDetector(
                                      onTap: () {
                                        setState1(() {
                                          selectedSerialNumbers.add(list[index]);
                                          list.removeAt(index);
                                        });
                                      },
                                      child: Text(list[index]),
                                    ),
                                  ).visible(list[index].contains(searchWord));
                                },
                              ),
                            ),
                          ),
                          const SizedBox(height: 20.0),
                          Text(lang.S.of(context).selectSerialNumber),
                          const SizedBox(height: 10.0),
                          Container(
                            width: 500,
                            height: 100,
                            decoration: BoxDecoration(border: Border.all(width: 1, color: Colors.grey), borderRadius: const BorderRadius.all(Radius.circular(10))),
                            child: GridView.builder(
                                shrinkWrap: true,
                                itemCount: selectedSerialNumbers.length,
                                itemBuilder: (BuildContext context, int index) {
                                  if (selectedSerialNumbers.isNotEmpty) {
                                    return Padding(
                                      padding: const EdgeInsets.all(10.0),
                                      child: Row(
                                        crossAxisAlignment: CrossAxisAlignment.center,
                                        children: [
                                          GestureDetector(
                                              onTap: () {
                                                setState1(() {
                                                  list.add(selectedSerialNumbers[index]);
                                                  selectedSerialNumbers.removeAt(index);
                                                });
                                              },
                                              child: const Icon(
                                                Icons.cancel_outlined,
                                                size: 15,
                                              )),
                                          Text(
                                            '${selectedSerialNumbers[index]},',
                                          ),
                                        ],
                                      ),
                                    );
                                  } else {
                                    return Text(lang.S.of(context).noSerialNumberFound);
                                  }
                                },
                                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: 3,
                                  childAspectRatio: 4,
                                  crossAxisSpacing: 1,
                                  mainAxisSpacing: 1,
                                )),
                          ),
                          const SizedBox(height: 20),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              Container(
                                  padding: const EdgeInsets.only(left: 30.0, right: 30.0, top: 10.0, bottom: 10.0),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(5.0),
                                    color: kRedTextColor,
                                  ),
                                  child: Text(
                                    lang.S.of(context).cancel,
                                    style: kTextStyle.copyWith(color: kWhite),
                                  )).onTap(() {
                                GoRouter.of(context).pop();
                              }),
                              const SizedBox(width: 10.0),
                              GestureDetector(
                                onTap: () {
                                  setState(() {
                                    AddToCartModel addToCartModel = AddToCartModel(
                                      productName: productModel.productName,
                                      warehouseName: productModel.warehouseName,
                                      warehouseId: productModel.warehouseId,
                                      productId: productModel.productCode,
                                      productImage: productModel.productPicture,
                                      productPurchasePrice: productModel.productPurchasePrice.toDouble(),
                                      subTotal: productPriceChecker(product: productModel, customerType: selectedCustomerType),
                                      serialNumber: selectedSerialNumbers,
                                      quantity: selectedSerialNumbers.isEmpty ? 1 : selectedSerialNumbers.length,
                                      stock: num.parse(productModel.productStock),
                                      productWarranty: productModel.warranty,
                                      subTaxes: productModel.subTaxes,
                                      excTax: productModel.excTax,
                                      groupTaxName: productModel.groupTaxName,
                                      groupTaxRate: productModel.groupTaxRate,
                                      incTax: productModel.incTax,
                                      margin: productModel.margin,
                                      taxType: productModel.taxType,
                                    );
                                    if (!uniqueCheckForSerial(code: productModel.productCode, newSerialNumbers: selectedSerialNumbers)) {
                                      if (productModel.productStock == '0') {
                                        EasyLoading.showError('Product Out Of Stock');
                                      } else {
                                        cartList.add(addToCartModel);
                                        addFocus();
                                      }
                                    }
                                  });
                                  GoRouter.of(context).pop();
                                },
                                child: Container(
                                  padding: const EdgeInsets.only(left: 30.0, right: 30.0, top: 10.0, bottom: 10.0),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(5.0),
                                    color: kBlueTextColor,
                                  ),
                                  child: Text(
                                    lang.S.of(context).submit,
                                    style: kTextStyle.copyWith(color: kWhite),
                                  ),
                                ),
                              )
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

  void showCalcPopUp() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return Dialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5.0),
              ),
              child: SizedBox(
                width: 300,
                height: MediaQuery.of(context).size.height * 0.5,
                child: const Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [CalcButton()],
                ),
              ),
            );
          },
        );
      },
    );
  }

  late StreamSubscription subscription;
  bool isDeviceConnected = false;
  bool isAlertSet = false;

  checkInternet() async {
    isDeviceConnected = await InternetConnection().hasInternetAccess;
    if (!isDeviceConnected) {
      showDialogBox();
      setState(() => isAlertSet = true);
    }
  }

  showDialogBox() => showCupertinoDialog<String>(
        context: context,
        builder: (BuildContext context) => CupertinoAlertDialog(
          title: Text(lang.S.of(context).noConnection),
          content: Text(lang.S.of(context).pleaseCheckYourInternetConnectivity),
          actions: <Widget>[
            TextButton(
              onPressed: () async {
                GoRouter.of(context).pop();
                setState(() => isAlertSet = false);
                isDeviceConnected = await InternetConnection().hasInternetAccess;
                if (!isDeviceConnected && isAlertSet == false) {
                  showDialogBox();
                  setState(() => isAlertSet = true);
                }
              },
              child: Text(lang.S.of(context).tryAgain),
            ),
          ],
        ),
      );

  Widget _buildCategoryItem(String title, String selectionValue) {
    final screenWidth = MediaQuery.of(context).size.width;
    final theme = Theme.of(context);
    return GestureDetector(
      onTap: () => setState(() {
        selectedCategory = selectionValue;
        isSelected = selectionValue;
      }),
      child: Padding(
        padding: EdgeInsets.only(
          top: 5,
          bottom: 4,
          right: screenWidth < 1240 ? 10 : 0,
        ),
        child: Container(
          width: screenWidth > 1240 ? double.infinity : null,
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(4.0),
            border: isSelected == selectionValue ? Border(left: BorderSide(color: kMainColor, width: 2)) : Border.all(color: kNeutral100),
            color: isSelected == selectionValue
                ? screenWidth < 1240
                    ? Colors.transparent
                    : kMainColor100
                : Colors.transparent,
          ),
          child: Text(
            title,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            style: theme.textTheme.titleSmall?.copyWith(
              color: isSelected == selectionValue ? kMainColor : kDarkGreyColor,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final currencyProvider = pro.Provider.of<CurrencyProvider>(context);
    final globalCurrency = currencyProvider.currency ?? '\$';
    final screenWidth = MediaQuery.of(context).size.width;
    final _screenSize = MediaQuery.of(context).size;
    final theme = Theme.of(context);
    List<String> allProductsNameList = [];
    List<String> allProductsCodeList = [];
    List<String> warehouseIdList = [];
    List<WarehouseBasedProductModel> warehouseBasedProductModel = [];
    List<ProductModel> productSerial;

    double totalTaxAmount = getAllTaxFromCartList(cart: cartList).fold(0, (sum, tax) {
      num taxRate = tax.taxRate ?? 0;
      return sum + (getTotalAmount().toDouble() * taxRate / 100);
    });

    String getDiscountAmount() {
      double subtotal = 0.0;
      for (var item in cartList) {
        subtotal = subtotal + (double.parse(item.subTotal) * item.quantity);
      }
      double total = subtotal + serviceCharge + totalTaxAmount;
      return total.toStringAsFixed(2);
    }

    return Consumer(
      builder: (context, consumerRef, __) {
        final wareHouseList = consumerRef.watch(warehouseProvider);
        final customerList = consumerRef.watch(allCustomerProvider);
        final personalData = consumerRef.watch(profileDetailsProvider);

        AsyncValue<List<ProductModel>> productList = consumerRef.watch(productProvider);

        return Scaffold(
          backgroundColor: kDarkWhite,
          body: SingleChildScrollView(
            physics: _screenSize.width < 1240
                ? ScrollPhysics()
                : getAllTaxFromCartList(cart: cartList).isNotEmpty
                    ? ScrollPhysics()
                    : NeverScrollableScrollPhysics(),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ResponsiveGridRow(rowSegments: 100, children: [
                      // Product add section
                      ResponsiveGridCol(
                        lg: 48,
                        md: 100,
                        xs: 100,
                        child: IntrinsicWidth(
                          child: Container(
                            decoration: BoxDecoration(
                              color: kWhite,
                            ),
                            child: Padding(
                              padding: const EdgeInsets.all(6),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  ResponsiveGridRow(rowSegments: 120, children: [
                                    // Customer selection
                                    ResponsiveGridCol(
                                      xs: 60,
                                      md: 60,
                                      lg: 60,
                                      child: customerList.when(data: (allCustomers) {
                                        List<String> listOfPhoneNumber = [];
                                        List<CustomerModel> customersList = [];
                                        for (var value1 in allCustomers) {
                                          listOfPhoneNumber.add(value1.phoneNumber.removeAllWhiteSpace().toLowerCase());
                                          if (value1.type != 'Supplier') {
                                            customersList.add(value1);
                                          }
                                        }
                                        return Padding(
                                          padding: const EdgeInsets.all(6.0),
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Row(
                                                mainAxisAlignment: MainAxisAlignment.start,
                                                children: [
                                                  Flexible(
                                                    child: DropdownButtonHideUnderline(child: getResult(customersList, globalCurrency)),
                                                  ),
                                                  GestureDetector(
                                                    onTap: () {
                                                      context.push(
                                                        '/add-customer',
                                                        extra: {
                                                          'typeOfCustomerAdd': 'Buyer',
                                                          'listOfPhoneNumber': listOfPhoneNumber,
                                                        },
                                                      );
                                                    },
                                                    child: Container(
                                                      height: 40,
                                                      width: 40,
                                                      decoration: BoxDecoration(
                                                        border: Border(
                                                          right: BorderSide(color: kNeutral300),
                                                          top: BorderSide(color: kNeutral300),
                                                          bottom: BorderSide(color: kNeutral300),
                                                        ),
                                                        borderRadius: BorderRadius.only(topRight: Radius.circular(5), bottomRight: Radius.circular(5)),
                                                        color: kMainColor50,
                                                      ),
                                                      child: const Center(
                                                        child: Icon(
                                                          FeatherIcons.userPlus,
                                                          size: 18.0,
                                                          color: kMainColor,
                                                        ),
                                                      ),
                                                    ),
                                                  )
                                                ],
                                              ),
                                              if (selectedUserId != null && selectedUserId != 'Guest')
                                                Column(
                                                  children: [
                                                    SizedBox(height: 2),
                                                    Text.rich(
                                                      TextSpan(text: '${lang.S.of(context).balance}: ', style: TextStyle(color: kTitleColor), children: [
                                                        TextSpan(
                                                            text: '$globalCurrency${myFormat.format(double.tryParse(previousDue) ?? 0)}',
                                                            style: TextStyle(color: Colors.red, fontWeight: FontWeight.w500))
                                                      ]),
                                                      style: theme.textTheme.bodyMedium,
                                                    )
                                                  ],
                                                )
                                            ],
                                          ),
                                        );
                                      }, error: (e, stack) {
                                        return Center(
                                          child: Text(e.toString()),
                                        );
                                      }, loading: () {
                                        return const Center(
                                          child: CircularProgressIndicator(),
                                        );
                                      }),
                                    ),
                                    // Warehouse selection
                                    ResponsiveGridCol(
                                      xs: 60,
                                      md: 60,
                                      lg: 60,
                                      child: wareHouseList.when(
                                        data: (warehouse) {
                                          return Padding(
                                            padding: const EdgeInsets.all(6.0),
                                            child: Theme(
                                              data: ThemeData(highlightColor: dropdownItemColor, focusColor: Colors.transparent, hoverColor: dropdownItemColor),
                                              child: DropdownButtonHideUnderline(
                                                child: getWare(list: warehouse ?? []),
                                              ),
                                            ),
                                          );
                                        },
                                        error: (e, stack) {
                                          return Center(
                                            child: Text(
                                              e.toString(),
                                            ),
                                          );
                                        },
                                        loading: () {
                                          return const Center(
                                            child: CircularProgressIndicator(),
                                          );
                                        },
                                      ),
                                    ),
                                  ]),
                                  selectedUserId != null && selectedUserId != 'Guest' ? SizedBox.shrink() : SizedBox(height: 10),
                                  Container(
                                    height: _screenSize.width < 720
                                        ? 720 - 410
                                        : selectedUserId == null
                                            ? _screenSize.height - 365
                                            : _screenSize.height - 380,
                                    decoration: const BoxDecoration(border: Border(bottom: BorderSide(width: 1, color: kNeutral300))),
                                    child: LayoutBuilder(
                                      builder: (BuildContext context, BoxConstraints constraints) {
                                        final kWidth = constraints.maxWidth;
                                        return RawScrollbar(
                                          thumbVisibility: true,
                                          controller: _horizontalScroll,
                                          thickness: 8.0,
                                          radius: const Radius.circular(5),
                                          child: SingleChildScrollView(
                                            scrollDirection: Axis.horizontal,
                                            controller: _horizontalScroll,
                                            child: ConstrainedBox(
                                              constraints: BoxConstraints(
                                                minWidth: kWidth,
                                                maxHeight: 200,
                                              ),
                                              child: Theme(
                                                data: theme.copyWith(dividerColor: Colors.transparent, dividerTheme: const DividerThemeData(color: Colors.transparent)),
                                                child: SingleChildScrollView(
                                                  child: DataTable(
                                                      columnSpacing: 10,
                                                      border: const TableBorder(
                                                        horizontalInside: BorderSide(
                                                          width: 1,
                                                          color: kNeutral300,
                                                        ),
                                                      ),
                                                      dividerThickness: 0.0,
                                                      dataRowColor: const WidgetStatePropertyAll(whiteColor),
                                                      headingRowColor: WidgetStateProperty.all(const Color(0xFFF8F3FF)),
                                                      showBottomBorder: false,
                                                      headingTextStyle: theme.textTheme.titleMedium,
                                                      dataTextStyle: theme.textTheme.bodyLarge,
                                                      columns: [
                                                        DataColumn(label: Text(lang.S.of(context).product)),
                                                        DataColumn(headingRowAlignment: MainAxisAlignment.center, label: Text(lang.S.of(context).quantity)),
                                                        DataColumn(headingRowAlignment: MainAxisAlignment.center, label: Text(lang.S.of(context).price)),
                                                        DataColumn(headingRowAlignment: MainAxisAlignment.center, label: Text(lang.S.of(context).subTotal)),
                                                        DataColumn(
                                                            headingRowAlignment: MainAxisAlignment.center,
                                                            label: Text(
                                                              lang.S.of(context).action,
                                                              textAlign: TextAlign.end,
                                                            )),
                                                      ],
                                                      rows: List.generate(cartList.length, (index) {
                                                        for (var item in cartList) {
                                                          print('--serial number-----${item.serialNumber}-----');
                                                        }
                                                        TextEditingController quantityController = TextEditingController(text: cartList[index].quantity.toString());
                                                        return DataRow(cells: [
                                                          // Product name
                                                          DataCell(
                                                            Row(
                                                              crossAxisAlignment: CrossAxisAlignment.start,
                                                              children: [
                                                                Text(
                                                                  cartList[index].productName ?? '',
                                                                  maxLines: 1,
                                                                  overflow: TextOverflow.ellipsis,
                                                                ),
                                                                SizedBox(width: 4),
                                                                Builder(
                                                                  builder: (BuildContext context) {
                                                                    // Find the product model
                                                                    ProductModel? productModel;
                                                                    for (var product in productList.value ?? []) {
                                                                      if (product.productCode == cartList[index].productId) {
                                                                        productModel = product;
                                                                        break;
                                                                      }
                                                                    }

                                                                    // Show the icon only if the product has serial numbers
                                                                    if (productModel != null && productModel.serialNumber.isNotEmpty) {
                                                                      return Padding(
                                                                        padding: const EdgeInsetsDirectional.only(top: 12),
                                                                        child: GestureDetector(
                                                                          onTap: () {
                                                                            showSerialNumberPopUp(productModel: productModel!);
                                                                          },
                                                                          child: HugeIcon(
                                                                            icon: HugeIcons.strokeRoundedPropertyEdit,
                                                                            color: kMainColor,
                                                                            size: 16,
                                                                          ),
                                                                        ),
                                                                      );
                                                                    }
                                                                    return const SizedBox.shrink();
                                                                  },
                                                                ),
                                                              ],
                                                            ),
                                                          ),
                                                          DataCell(Center(
                                                            child: Row(
                                                              mainAxisAlignment: MainAxisAlignment.center,
                                                              children: [
                                                                HugeIcon(
                                                                  icon: HugeIcons.strokeRoundedRemoveSquare,
                                                                  color: kNeutral400,
                                                                  size: 25,
                                                                ).onTap(() {
                                                                  setState(() {
                                                                    cartList[index].quantity > 1 ? cartList[index].quantity-- : cartList[index].quantity = 1;
                                                                  });
                                                                }),
                                                                const SizedBox(width: 2),
                                                                SizedBox(
                                                                  width: 50,
                                                                  child: TextFormField(
                                                                    controller: quantityController,
                                                                    textAlign: TextAlign.center,
                                                                    focusNode: productFocusNode[index],
                                                                    decoration: InputDecoration(
                                                                      border: InputBorder.none,
                                                                      enabledBorder: InputBorder.none,
                                                                      focusedBorder: InputBorder.none,
                                                                    ),
                                                                    onChanged: (value) {
                                                                      if (cartList[index].stock! < num.parse(value)) {
                                                                        EasyLoading.showError('Out of Stock');
                                                                        quantityController.clear();
                                                                      } else if (value == '') {
                                                                        cartList[index].quantity = 1;
                                                                      } else if (value == '0') {
                                                                        cartList[index].quantity = 1;
                                                                      } else {
                                                                        cartList[index].quantity = num.parse(value);
                                                                      }
                                                                    },
                                                                    onFieldSubmitted: (value) {
                                                                      if (value == '') {
                                                                        setState(() {
                                                                          cartList[index].quantity = 1;
                                                                        });
                                                                      } else {
                                                                        setState(() {
                                                                          cartList[index].quantity = num.parse(value);
                                                                        });
                                                                      }
                                                                    },
                                                                  ),
                                                                ),
                                                                const SizedBox(width: 2),
                                                                StatefulBuilder(
                                                                  builder: (context, setStateIcon) {
                                                                    _tappedStates[index] ??= false;
                                                                    return HugeIcon(
                                                                      icon: HugeIcons.strokeRoundedPlusSignSquare,
                                                                      color: _tappedStates[index]! ? kMainColor : kNeutral400,
                                                                      size: 25,
                                                                    ).onTap(() {
                                                                      if (cartList[index].quantity < cartList[index].stock!) {
                                                                        setState(() {
                                                                          cartList[index].quantity += 1;
                                                                          toast(cartList[index].quantity.toString());
                                                                        });
                                                                        setStateIcon(() {
                                                                          _tappedStates[index] = true;
                                                                        });
                                                                        Future.delayed(Duration(milliseconds: 300), () {
                                                                          setStateIcon(() {
                                                                            _tappedStates[index] = false;
                                                                          });
                                                                        });
                                                                      } else {
                                                                        EasyLoading.showError('Out of Stock');
                                                                      }
                                                                    });
                                                                  },
                                                                ),
                                                              ],
                                                            ),
                                                          )),
                                                          DataCell(
                                                            Center(
                                                              child: Text(
                                                                myFormat.format(double.tryParse(cartList[index].subTotal) ?? 0),
                                                              ),
                                                            ),
                                                          ),
                                                          DataCell(
                                                            Center(
                                                              child: Text(
                                                                '$globalCurrency${myFormat.format(double.tryParse((double.parse(cartList[index].subTotal) * cartList[index].quantity).toStringAsFixed(2)) ?? 0)}',
                                                              ),
                                                            ),
                                                          ),
                                                          DataCell(
                                                            Align(
                                                              alignment: Alignment.center,
                                                              child: const Icon(
                                                                Icons.close_sharp,
                                                                color: redColor,
                                                                size: 20,
                                                              ).onTap(() {
                                                                setState(() {
                                                                  cartList.removeAt(index);
                                                                  productFocusNode.removeAt(index);
                                                                });
                                                              }),
                                                            ),
                                                          ),
                                                        ]);
                                                      })),
                                                ),
                                              ),
                                            ),
                                          ),
                                        );
                                      },
                                    ),
                                  ),

                                  /// Price section
                                  Padding(
                                    padding: const EdgeInsets.all(10.0),
                                    child: Column(
                                      mainAxisSize: MainAxisSize.min,
                                      crossAxisAlignment: CrossAxisAlignment.end,
                                      children: [
                                        /// Total
                                        ResponsiveGridRow(children: [
                                          ResponsiveGridCol(
                                            xs: 12,
                                            md: 6,
                                            lg: 6,
                                            child: Padding(
                                              padding: EdgeInsets.only(bottom: screenWidth < 577 ? 12 : 0),
                                              child: Text(
                                                'Total Item: ${cartList.length}',
                                                style: theme.textTheme.titleMedium,
                                              ),
                                            ),
                                          ),
                                          ResponsiveGridCol(
                                              xs: 12,
                                              md: 6,
                                              lg: 6,
                                              child: Row(
                                                children: [
                                                  Flexible(
                                                    fit: FlexFit.tight,
                                                    flex: 9,
                                                    child: Padding(
                                                      padding: const EdgeInsets.only(right: 12),
                                                      child: Text(
                                                        'Sub Total',
                                                        textAlign: TextAlign.start,
                                                        style: theme.textTheme.titleMedium,
                                                      ),
                                                    ),
                                                  ),
                                                  Flexible(
                                                      fit: FlexFit.tight,
                                                      flex: 11,
                                                      child: Container(
                                                        height: 33,
                                                        width: screenWidth,
                                                        decoration: BoxDecoration(
                                                          color: kMainColor.withValues(alpha: 0.1),
                                                          borderRadius: BorderRadius.circular(4),
                                                        ),
                                                        child: Align(
                                                          alignment: Alignment.centerRight,
                                                          child: Padding(
                                                            padding: const EdgeInsets.symmetric(horizontal: 16),
                                                            child: Text(
                                                              '$globalCurrency ${myFormat.format(double.tryParse((getTotalAmount().toDouble() + serviceCharge - discountAmount).toStringAsFixed(2)) ?? 0)}',
                                                              style: theme.textTheme.titleMedium?.copyWith(color: kMainColor),
                                                            ),
                                                          ),
                                                        ),
                                                      ))
                                                ],
                                              ))
                                        ]),
                                        const SizedBox(height: 10.0),

                                        /// Taxes
                                        ResponsiveGridRow(children: [
                                          ResponsiveGridCol(
                                            xs: 12,
                                            md: 6,
                                            lg: 6,
                                            child: const SizedBox.shrink(),
                                          ),
                                          ResponsiveGridCol(
                                            xs: 12,
                                            md: 6,
                                            lg: 6,
                                            child: SizedBox(
                                              child: ListView.builder(
                                                itemCount: getAllTaxFromCartList(cart: cartList).length,
                                                shrinkWrap: true,
                                                itemBuilder: (context, index) {
                                                  return Container(
                                                    height: 33,
                                                    margin: const EdgeInsets.only(top: 5, bottom: 5),
                                                    child: Row(
                                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                      children: [
                                                        Flexible(
                                                          fit: FlexFit.tight,
                                                          flex: 9,
                                                          child: Padding(
                                                            padding: const EdgeInsets.only(right: 12),
                                                            child: Text(
                                                              getAllTaxFromCartList(cart: cartList)[index].name,
                                                              textAlign: TextAlign.start,
                                                              style: theme.textTheme.titleMedium,
                                                            ),
                                                          ),
                                                        ),
                                                        Flexible(
                                                          fit: FlexFit.tight,
                                                          flex: 11,
                                                          child: SizedBox(
                                                            height: 33.0,
                                                            child: Center(
                                                              child: AppTextField(
                                                                initialValue: getAllTaxFromCartList(cart: cartList)[index].taxRate.toString(),
                                                                readOnly: true,
                                                                textAlign: TextAlign.right,
                                                                decoration: InputDecoration(
                                                                  contentPadding: const EdgeInsets.only(right: 6.0),
                                                                  hintText: '0',
                                                                  border: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: Color(0xFFff5f00))),
                                                                  enabledBorder: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: Color(0xFFff5f00))),
                                                                  disabledBorder: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: Color(0xFFff5f00))),
                                                                  focusedBorder: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: Color(0xFFff5f00))),
                                                                  prefixIconConstraints: const BoxConstraints(maxWidth: 30.0, minWidth: 30.0),
                                                                  prefixIcon: Container(
                                                                    alignment: Alignment.center,
                                                                    height: 33,
                                                                    decoration: const BoxDecoration(
                                                                        color: Color(0xFFff5f00),
                                                                        borderRadius: BorderRadius.only(topLeft: Radius.circular(4.0), bottomLeft: Radius.circular(4.0))),
                                                                    child: const Text(
                                                                      '%',
                                                                      style: TextStyle(fontSize: 20.0, color: Colors.white),
                                                                    ),
                                                                  ),
                                                                ),
                                                                textFieldType: TextFieldType.NUMBER,
                                                              ),
                                                            ),
                                                          ),
                                                        ),
                                                      ],
                                                    ),
                                                  );
                                                },
                                              ),
                                            ),
                                          ),
                                        ]),
                                        const SizedBox(height: 10.0),

                                        /// Shipping cost
                                        ResponsiveGridRow(children: [
                                          ResponsiveGridCol(
                                            xs: 12,
                                            md: 6,
                                            lg: 6,
                                            child: const SizedBox.shrink(),
                                          ),
                                          ResponsiveGridCol(
                                            xs: 12,
                                            md: 6,
                                            lg: 6,
                                            child: SizedBox(
                                              child: Row(
                                                mainAxisAlignment: MainAxisAlignment.end,
                                                children: [
                                                  Flexible(
                                                    fit: FlexFit.tight,
                                                    flex: 9,
                                                    child: Padding(
                                                      padding: const EdgeInsets.only(right: 12),
                                                      child: Text(
                                                        'Shipping Cost',
                                                        textAlign: TextAlign.start,
                                                        style: theme.textTheme.titleMedium,
                                                      ),
                                                    ),
                                                  ),
                                                  Flexible(
                                                    flex: 11,
                                                    fit: FlexFit.tight,
                                                    child: SizedBox(
                                                      width: screenWidth,
                                                      height: 33,
                                                      child: TextFormField(
                                                        textAlign: TextAlign.end,
                                                        initialValue: serviceCharge.toString(),
                                                        onChanged: (value) {
                                                          setState(() {
                                                            serviceCharge = value.toDouble();
                                                          });
                                                        },
                                                        decoration: InputDecoration(
                                                          border: OutlineInputBorder(),
                                                          hintText: 'Enter Amount',
                                                          contentPadding: EdgeInsets.all(7.0),
                                                        ),
                                                        keyboardType: TextInputType.number,
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                        ]),
                                        const SizedBox(height: 10.0),

                                        /// Discount
                                        ResponsiveGridRow(children: [
                                          ResponsiveGridCol(
                                            xs: 12,
                                            md: 6,
                                            lg: 6,
                                            child: const SizedBox.shrink(),
                                          ),
                                          ResponsiveGridCol(
                                            xs: 12,
                                            md: 6,
                                            lg: 6,
                                            child: Row(
                                              mainAxisAlignment: MainAxisAlignment.end,
                                              children: [
                                                Flexible(
                                                  fit: FlexFit.tight,
                                                  flex: 9,
                                                  child: Padding(
                                                    padding: const EdgeInsets.only(right: 12),
                                                    child: Text(
                                                      lang.S.of(context).discount,
                                                      textAlign: TextAlign.start,
                                                      style: theme.textTheme.titleMedium,
                                                    ),
                                                  ),
                                                ),
                                                Flexible(
                                                  fit: FlexFit.tight,
                                                  flex: 11,
                                                  child: Row(
                                                    children: [
                                                      Flexible(
                                                        child: SizedBox(
                                                          height: 33.0,
                                                          child: AppTextField(
                                                            controller: discountPercentageEditingController,
                                                            onChanged: (value) {
                                                              if (value == '') {
                                                                setState(() {
                                                                  discountAmountEditingController.text = 0.toString();
                                                                });
                                                              } else {
                                                                if (value.toInt() <= 100) {
                                                                  setState(() {
                                                                    double totalBeforeDiscount = double.parse(getDiscountAmount());
                                                                    discountAmount = double.parse(((value.toDouble() / 100) * totalBeforeDiscount).toStringAsFixed(1));
                                                                    discountAmountEditingController.text = discountAmount.toString();
                                                                  });
                                                                } else {
                                                                  setState(() {
                                                                    discountAmount = 0;
                                                                    discountAmountEditingController.clear();
                                                                    discountPercentageEditingController.clear();
                                                                  });
                                                                  EasyLoading.showError('Enter a valid Discount');
                                                                }
                                                              }
                                                            },
                                                            textAlign: TextAlign.right,
                                                            decoration: InputDecoration(
                                                              contentPadding: const EdgeInsets.only(right: 6.0),
                                                              hintText: '0',
                                                              border: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: Color(0xFFff5f00))),
                                                              enabledBorder: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: Color(0xFFff5f00))),
                                                              disabledBorder: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: Color(0xFFff5f00))),
                                                              focusedBorder: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: Color(0xFFff5f00))),
                                                              prefixIconConstraints: const BoxConstraints(maxWidth: 30.0, minWidth: 30.0),
                                                              prefixIcon: Container(
                                                                alignment: Alignment.center,
                                                                height: 33,
                                                                decoration: const BoxDecoration(
                                                                    color: Color(0xFFff5f00),
                                                                    borderRadius: BorderRadius.only(topLeft: Radius.circular(4.0), bottomLeft: Radius.circular(4.0))),
                                                                child: const Text(
                                                                  '%',
                                                                  style: TextStyle(fontSize: 20.0, color: Colors.white),
                                                                ),
                                                              ),
                                                            ),
                                                            textFieldType: TextFieldType.NUMBER,
                                                          ),
                                                        ),
                                                      ),
                                                      const SizedBox(
                                                        width: 9.0,
                                                      ),
                                                      Flexible(
                                                        child: SizedBox(
                                                          height: 33.0,
                                                          child: AppTextField(
                                                            controller: discountAmountEditingController,
                                                            onChanged: (value) {
                                                              if (value == '') {
                                                                setState(() {
                                                                  discountAmount = 0;
                                                                  discountPercentageEditingController.text = 0.toString();
                                                                });
                                                              } else {
                                                                double totalBeforeDiscount = double.parse(getDiscountAmount());
                                                                if (value.toDouble() <= totalBeforeDiscount) {
                                                                  setState(() {
                                                                    discountAmount = double.parse(value);
                                                                    discountPercentageEditingController.text = ((discountAmount * 100) / totalBeforeDiscount).toStringAsFixed(1);
                                                                  });
                                                                } else {
                                                                  setState(() {
                                                                    discountAmount = 0;
                                                                    discountPercentageEditingController.clear();
                                                                    discountAmountEditingController.clear();
                                                                  });
                                                                  EasyLoading.showError('Enter a valid Discount');
                                                                }
                                                              }
                                                            },
                                                            textAlign: TextAlign.right,
                                                            decoration: InputDecoration(
                                                              contentPadding: const EdgeInsets.only(right: 6.0),
                                                              hintText: '0',
                                                              border: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: kMainColor)),
                                                              enabledBorder: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: kMainColor)),
                                                              disabledBorder: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: kMainColor)),
                                                              focusedBorder: const OutlineInputBorder(gapPadding: 0.0, borderSide: BorderSide(color: kMainColor)),
                                                              prefixIconConstraints: const BoxConstraints(maxWidth: 30.0, minWidth: 30.0),
                                                              prefixIcon: Container(
                                                                alignment: Alignment.center,
                                                                height: 33,
                                                                decoration: const BoxDecoration(
                                                                    color: kMainColor,
                                                                    borderRadius: BorderRadius.only(topLeft: Radius.circular(4.0), bottomLeft: Radius.circular(4.0))),
                                                                child: Text(
                                                                  currency,
                                                                  style: const TextStyle(fontSize: 20.0, color: Colors.white),
                                                                ),
                                                              ),
                                                            ),
                                                            textFieldType: TextFieldType.NUMBER,
                                                          ),
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ]),
                                        const SizedBox(height: 10.0),

                                        const SizedBox(height: 18.0),

                                        /// Buttons
                                        ResponsiveGridRow(children: [
                                          ResponsiveGridCol(
                                              xs: 6,
                                              md: 4,
                                              lg: 4,
                                              child: Padding(
                                                padding: EdgeInsets.only(right: 12, bottom: screenWidth < 577 ? 12 : 0),
                                                child: OutlinedButton(
                                                  style: ElevatedButton.styleFrom(padding: EdgeInsets.zero, minimumSize: Size.fromHeight(36), side: BorderSide(color: Colors.red)),
                                                  onPressed: () {
                                                    GoRouter.of(context).pop();
                                                  },
                                                  child: Text(
                                                    lang.S.of(context).cancel,
                                                    style: TextStyle(color: Colors.red),
                                                  ),
                                                ),
                                              )),
                                          ResponsiveGridCol(
                                              xs: 6,
                                              md: 4,
                                              lg: 4,
                                              child: Padding(
                                                padding: EdgeInsets.only(right: screenWidth < 577 ? 0 : 12, bottom: screenWidth < 577 ? 12 : 0),
                                                child: OutlinedButton(
                                                  style: OutlinedButton.styleFrom(
                                                      foregroundColor: Colors.black,
                                                      padding: EdgeInsets.zero,
                                                      minimumSize: Size.fromHeight(36),
                                                      side: BorderSide(color: Colors.black)),
                                                  onPressed: () async {
                                                    if (await checkUserRolePermission(type: 'quotation-create')) {
                                                      if (await Subscription.subscriptionChecker(item: 'Sales')) {
                                                        if (cartList.isEmpty) {
                                                          EasyLoading.showError('Please Add Some Product first');
                                                        } else {
                                                          showDialog(
                                                              barrierDismissible: false,
                                                              context: context,
                                                              builder: (BuildContext dialogContext) {
                                                                return Padding(
                                                                  padding: const EdgeInsets.all(10.0),
                                                                  child: Center(
                                                                    child: Container(
                                                                      width: 500,
                                                                      decoration: const BoxDecoration(
                                                                        color: Colors.white,
                                                                        borderRadius: BorderRadius.all(
                                                                          Radius.circular(15),
                                                                        ),
                                                                      ),
                                                                      child: Padding(
                                                                        padding: const EdgeInsets.all(20.0),
                                                                        child: Column(
                                                                          mainAxisSize: MainAxisSize.min,
                                                                          crossAxisAlignment: CrossAxisAlignment.center,
                                                                          mainAxisAlignment: MainAxisAlignment.center,
                                                                          children: [
                                                                            Text(
                                                                              lang.S.of(context).areYouWantToCreateThisQuation,
                                                                              style: theme.textTheme.headlineSmall?.copyWith(
                                                                                fontWeight: FontWeight.w600,
                                                                              ),
                                                                              textAlign: TextAlign.center,
                                                                            ),
                                                                            const SizedBox(height: 20),
                                                                            ResponsiveGridRow(children: [
                                                                              ResponsiveGridCol(
                                                                                lg: 6,
                                                                                md: 6,
                                                                                xs: 6,
                                                                                child: Padding(
                                                                                  padding: const EdgeInsets.all(10.0),
                                                                                  child: ElevatedButton(
                                                                                    style: ElevatedButton.styleFrom(
                                                                                      backgroundColor: Colors.red,
                                                                                    ),
                                                                                    child: Text(
                                                                                      lang.S.of(context).cancel,
                                                                                      style: const TextStyle(color: Colors.white),
                                                                                    ),
                                                                                    onPressed: () {
                                                                                      GoRouter.of(dialogContext).pop();
                                                                                    },
                                                                                  ),
                                                                                ),
                                                                              ),
                                                                              ResponsiveGridCol(
                                                                                  md: 6,
                                                                                  xs: 6,
                                                                                  lg: 6,
                                                                                  child: Padding(
                                                                                    padding: const EdgeInsets.all(10.0),
                                                                                    child: ElevatedButton(
                                                                                      child: Text(
                                                                                        lang.S.of(context).create,
                                                                                      ),
                                                                                      onPressed: () async {
                                                                                        SaleTransactionModel transitionModel = SaleTransactionModel(
                                                                                          customerName: selectedUserName.customerName,
                                                                                          customerGst: selectedUserName.gst,
                                                                                          customerType: selectedUserName.type,
                                                                                          customerImage: selectedUserName.profilePicture,
                                                                                          customerAddress: selectedUserName.customerAddress,
                                                                                          customerPhone: selectedUserName.phoneNumber,
                                                                                          sendWhatsappMessage: selectedUserName.receiveWhatsappUpdates ?? false,
                                                                                          invoiceNumber: widget.personalInformationModel.saleInvoiceCounter.toString(),
                                                                                          purchaseDate: DateTime.now().toString(),
                                                                                          productList: cartList,
                                                                                          totalAmount: double.parse(
                                                                                              (getTotalAmount().toDouble() + serviceCharge - discountAmount).toStringAsFixed(1)),
                                                                                          discountAmount: discountAmount,
                                                                                          serviceCharge: serviceCharge,
                                                                                          vat: 0,
                                                                                        );

                                                                                        try {
                                                                                          EasyLoading.show(status: 'Loading...', dismissOnTap: false);
                                                                                          DatabaseReference ref =
                                                                                              FirebaseDatabase.instance.ref("${await getUserID()}/Sales Quotation");

                                                                                          transitionModel.isPaid = false;
                                                                                          transitionModel.dueAmount = 0;
                                                                                          transitionModel.lossProfit = 0;
                                                                                          transitionModel.returnAmount = 0;
                                                                                          transitionModel.paymentType = 'Just Quotation';
                                                                                          transitionModel.sellerName = isSubUser ? constSubUserTitle : 'Admin';

                                                                                          await ref.push().set(transitionModel.toJson());

                                                                                          updateInvoice(
                                                                                              typeOfInvoice: 'saleInvoiceCounter', invoice: transitionModel.invoiceNumber.toInt());

                                                                                          consumerRef.refresh(profileDetailsProvider);

                                                                                          EasyLoading.showSuccess('Added Successfully');
                                                                                          await GeneratePdfAndPrint()
                                                                                              .printQuotationInvoice(
                                                                                                  personalInformationModel: widget.personalInformationModel,
                                                                                                  saleTransactionModel: transitionModel,
                                                                                                  context: context)
                                                                                              .then((_) {
                                                                                            if (context.mounted) {
                                                                                              final timestamp = DateTime.now().millisecondsSinceEpoch;
                                                                                              context.go('/sales/pos-sales?forceRefresh=$timestamp');
                                                                                            }
                                                                                          });
                                                                                          GoRouter.of(dialogContext).pop();
                                                                                        } catch (e) {
                                                                                          EasyLoading.dismiss();
                                                                                          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.toString())));
                                                                                        }
                                                                                      },
                                                                                    ),
                                                                                  ))
                                                                            ]),
                                                                          ],
                                                                        ),
                                                                      ),
                                                                    ),
                                                                  ),
                                                                );
                                                              });
                                                        }
                                                      } else {
                                                        EasyLoading.showError('Update your plan first\nSale Limit is over.');
                                                      }
                                                    }
                                                  },
                                                  child: Text(
                                                    lang.S.of(context).quotation,
                                                    style: TextStyle(color: Colors.black),
                                                  ),
                                                ),
                                              )),
                                          ResponsiveGridCol(
                                              xs: 12,
                                              md: 4,
                                              lg: 4,
                                              child: Padding(
                                                padding: EdgeInsets.only(right: screenWidth < 577 ? 0 : 12, bottom: screenWidth < 577 ? 12 : 0),
                                                child: ElevatedButton(
                                                  style: ElevatedButton.styleFrom(
                                                    padding: EdgeInsets.zero,
                                                    minimumSize: Size.fromHeight(36),
                                                    backgroundColor: kMainColor,
                                                  ),
                                                  onPressed: () async {
                                                    if (await checkUserRolePermission(type: 'pos-sale-create')) {
                                                      if (await Subscription.subscriptionChecker(item: 'Sales')) {
                                                        // if (cartList.isEmpty) {
                                                        //   EasyLoading.showError('Please Add Some Product first');
                                                        // } else {
                                                        //   SaleTransactionModel transitionModel = SaleTransactionModel(
                                                        //     customerName: selectedUserName.customerName,
                                                        //     customerType: selectedUserName.type,
                                                        //     customerGst: selectedUserName.gst,
                                                        //     customerImage: selectedUserName.profilePicture,
                                                        //     customerAddress: selectedUserName.customerAddress,
                                                        //     customerPhone: selectedUserName.phoneNumber,
                                                        //     invoiceNumber: widget.transitionModel.invoiceNumber,
                                                        //     purchaseDate: DateTime.now().toString(),
                                                        //     productList: cartList,
                                                        //     totalAmount: double.parse((getTotalAmount().toDouble() + serviceCharge - discountAmount).toStringAsFixed(1)),
                                                        //     discountAmount: double.parse(discountAmount.toStringAsFixed(2)),
                                                        //     serviceCharge: double.parse(serviceCharge.toStringAsFixed(2)),
                                                        //     vat: 0,
                                                        //   );
                                                        //   context.push(
                                                        //     '/sales/show-payment-popup',
                                                        //     extra: {
                                                        //       'transitionModel': transitionModel,
                                                        //       'isFromQuotation': true,
                                                        //     },
                                                        //   );
                                                        // }
                                                        if (cartList.isEmpty) {
                                                          EasyLoading.showError(lang.S.of(context).pleaseAddSomeProductFirst);
                                                        } else {
                                                          SaleTransactionModel transitionModel = SaleTransactionModel(
                                                            dueAmount: widget.transitionModel.dueAmount,
                                                            customerAddress: widget.transitionModel.customerAddress,
                                                            customerImage: widget.transitionModel.customerImage,
                                                            customerGst: widget.transitionModel.customerGst,
                                                            customerName: widget.transitionModel.customerName,
                                                            customerType: widget.transitionModel.customerType,
                                                            customerPhone: widget.transitionModel.customerPhone,
                                                            invoiceNumber: widget.transitionModel.invoiceNumber,
                                                            purchaseDate: widget.transitionModel.purchaseDate,
                                                            productList: cartList,
                                                            discountAmount: discountAmount,
                                                            serviceCharge: serviceCharge,
                                                            vat: 0,
                                                            totalAmount: double.parse((getTotalAmount().toDouble() + serviceCharge - discountAmount).toStringAsFixed(1)),
                                                          );
                                                          ShowEditPaymentPopUp(
                                                            newTransitionModel: transitionModel,
                                                            oldTransitionModel: widget.transitionModel,
                                                            previousPaid: widget.transitionModel.totalAmount! - widget.transitionModel.dueAmount!.toDouble(),
                                                            decreaseStockList: decreaseStockList,
                                                            pastProducts: pastProducts,
                                                            saleListPopUpContext: widget.popUpContext,
                                                          ).launch(context);
                                                        }
                                                      } else {
                                                        EasyLoading.showError('Update your plan first\nSale Limit is over.');
                                                      }
                                                    }
                                                  },
                                                  child: Text(
                                                    lang.S.of(context).payment,
                                                  ),
                                                ),
                                              )),
                                        ]),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                      // Product category section
                      ResponsiveGridCol(
                        lg: 12,
                        md: 100,
                        xs: 100,
                        child: Padding(
                          padding: EdgeInsets.symmetric(horizontal: screenWidth < 1240 ? 0 : 8, vertical: screenWidth > 1240 ? 0 : 8),
                          child: Consumer(
                            builder: (_, ref, watch) {
                              AsyncValue<List<CategoryModel>> categoryList = ref.watch(categoryProvider);
                              return categoryList.when(data: (category) {
                                return Container(
                                  height: _screenSize.width < 1240
                                      ? 110
                                      : _screenSize.width < 720
                                          ? 720 - 142
                                          : _screenSize.height - 78,
                                  padding: const EdgeInsets.all(8.0),
                                  decoration: BoxDecoration(
                                    color: kWhite,
                                  ),
                                  child: SingleChildScrollView(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text('Categories', style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w500)),
                                        const SizedBox(height: 12.61),
                                        if (_screenSize.width > 1240) _buildCategoryItem('All Category', 'Categories'),
                                        SizedBox(
                                          height: screenWidth < 1240 ? 50 : null,
                                          child: ListView.builder(
                                            scrollDirection: screenWidth < 1240 ? Axis.horizontal : Axis.vertical,
                                            itemCount: category.length,
                                            shrinkWrap: true,
                                            itemBuilder: (_, i) => Wrap(
                                              direction: Axis.horizontal,
                                              children: [
                                                if (_screenSize.width < 1240 && i == 0) ...[
                                                  _buildCategoryItem('All Category', 'Categories'),
                                                  const SizedBox(width: 5),
                                                ],
                                                _buildCategoryItem(category[i].categoryName, category[i].categoryName),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              }, error: (e, stack) {
                                return Center(
                                  child: Text(e.toString()),
                                );
                              }, loading: () {
                                return const Center(
                                  child: CircularProgressIndicator(),
                                );
                              });
                            },
                          ),
                        ),
                      ),
                      // Product list
                      ResponsiveGridCol(
                        lg: 40,
                        md: 100,
                        xs: 100,
                        child: Padding(
                          padding: EdgeInsetsDirectional.only(start: screenWidth < 1240 ? 8 : 0, end: 8, top: 8, bottom: 8),
                          child: Column(
                            children: [
                              // Search product
                              productList.when(data: (product) {
                                for (var element in product) {
                                  allProductsNameList.add(element.productName.removeAllWhiteSpace().toLowerCase());
                                  allProductsCodeList.add(element.productCode.removeAllWhiteSpace().toLowerCase());
                                  warehouseIdList.add(element.warehouseId.removeAllWhiteSpace().toLowerCase());
                                  warehouseBasedProductModel.add(WarehouseBasedProductModel(element.productName, element.warehouseId));
                                }
                                return SizedBox(
                                  height: 40,
                                  child: AppTextField(
                                    controller: nameCodeCategoryController,
                                    showCursor: true,
                                    focus: nameFocus,
                                    autoFocus: true,
                                    cursorColor: kTitleColor,
                                    onChanged: (value) {
                                      setState(() {
                                        searchProductCode = value.toLowerCase();
                                        selectedCategory = 'Categories';
                                        isSelected = "Categories";
                                      });
                                    },
                                    onFieldSubmitted: (value) {
                                      if (value != '') {
                                        if (product.isEmpty) {
                                          EasyLoading.showError('No Product Found');
                                        }
                                        for (int i = 0; i < product.length; i++) {
                                          if (product[i].productCode == value) {
                                            AddToCartModel addToCartModel = AddToCartModel(
                                              productName: product[i].productName,
                                              warehouseName: product[i].warehouseName,
                                              warehouseId: product[i].warehouseId,
                                              productId: product[i].productCode,
                                              productImage: product[i].productPicture,
                                              productPurchasePrice: product[i].productPurchasePrice.toDouble(),
                                              subTotal: productPriceChecker(product: product[i], customerType: selectedCustomerType),
                                              stock: num.parse(product[i].productStock),
                                              productWarranty: product[i].warranty,
                                              serialNumber: [],
                                              subTaxes: product[i].subTaxes,
                                              excTax: product[i].excTax,
                                              groupTaxName: product[i].groupTaxName,
                                              groupTaxRate: product[i].groupTaxRate,
                                              incTax: product[i].incTax,
                                              margin: product[i].margin,
                                              taxType: product[i].taxType,
                                            );
                                            setState(() {
                                              if (!uniqueCheck(product[i].productCode)) {
                                                cartList.add(addToCartModel);
                                                addFocus();
                                                nameCodeCategoryController.clear();
                                                nameFocus.requestFocus();
                                                searchProductCode = '';
                                              } else {
                                                nameCodeCategoryController.clear();
                                                nameFocus.requestFocus();
                                                searchProductCode = '';
                                              }
                                            });
                                            break;
                                          }
                                          if (i + 1 == product.length) {
                                            nameCodeCategoryController.clear();
                                            nameFocus.requestFocus();
                                            EasyLoading.showError('Not found');
                                            setState(() {
                                              searchProductCode = '';
                                            });
                                          }
                                        }
                                      }
                                    },
                                    textFieldType: TextFieldType.NAME,
                                    decoration: InputDecoration(
                                      filled: true,
                                      fillColor: Colors.white,
                                      enabledBorder: OutlineInputBorder(
                                        borderSide: BorderSide(color: kNeutral300),
                                      ),
                                      prefixIconConstraints: BoxConstraints(
                                        minHeight: 15,
                                        minWidth: 15,
                                      ),
                                      prefixIcon: Padding(
                                        padding: const EdgeInsetsDirectional.only(start: 10),
                                        child: Icon(MdiIcons.barcode, color: kTitleColor, size: 20.0),
                                      ),
                                      hintText: 'Search product name or code',
                                      border: InputBorder.none,
                                    ),
                                  ),
                                );
                              }, error: (e, stack) {
                                return Center(
                                  child: Text(e.toString()),
                                );
                              }, loading: () {
                                return const Center(
                                  child: CircularProgressIndicator(),
                                );
                              }),
                              SizedBox(height: 8),
                              productList.when(data: (products) {
                                List<ProductModel> showProductVsCategory = [];
                                if (selectedCategory == 'Categories') {
                                  for (var element in products) {
                                    if (element.productCode.toLowerCase().contains(searchProductCode) ||
                                        element.productCategory.toLowerCase().contains(searchProductCode) ||
                                        element.productName.toLowerCase().contains(searchProductCode)) {
                                      productPriceChecker(product: element, customerType: selectedCustomerType) != '0' &&
                                              ((selectedWareHouse?.warehouseName == 'InHouse' && element.warehouseId == '') ? true : selectedWareHouse?.id == element.warehouseId)
                                          ? showProductVsCategory.add(element)
                                          : null;
                                    }
                                  }
                                } else {
                                  for (var element in products) {
                                    if (element.productCategory == selectedCategory) {
                                      productPriceChecker(product: element, customerType: selectedCustomerType) != '0' &&
                                              ((selectedWareHouse?.warehouseName == 'InHouse' && element.warehouseId == '') ? true : selectedWareHouse?.id == element.warehouseId)
                                          ? showProductVsCategory.add(element)
                                          : null;
                                    }
                                  }
                                }

                                final filteredProducts = showProductVsCategory.where((product) => product.productStock != '0').toList();

                                return filteredProducts.isNotEmpty
                                    ? SizedBox(
                                        height: context.height() - 135,
                                        child: Container(
                                          decoration: const BoxDecoration(
                                            color: kDarkWhite,
                                          ),
                                          child: GridView.builder(
                                            gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
                                              maxCrossAxisExtent: 137,
                                              mainAxisExtent: 170,
                                              mainAxisSpacing: 10,
                                              crossAxisSpacing: 10,
                                            ),
                                            itemCount: filteredProducts.length,
                                            itemBuilder: (_, i) {
                                              return Container(
                                                width: 137.0,
                                                height: 170.0,
                                                decoration: BoxDecoration(
                                                  borderRadius: BorderRadius.circular(4.0),
                                                  color: kWhite,
                                                ),
                                                child: Column(
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                  children: [
                                                    /// Image and stock
                                                    Stack(
                                                      alignment: Alignment.topLeft,
                                                      children: [
                                                        Container(
                                                          height: 110,
                                                          width: MediaQuery.of(context).size.width,
                                                          alignment: Alignment.center,
                                                          decoration: const BoxDecoration(
                                                            borderRadius: BorderRadius.only(
                                                              topLeft: Radius.circular(10.0),
                                                              topRight: Radius.circular(10.0),
                                                            ),
                                                            color: Colors.white,
                                                          ),
                                                          clipBehavior: Clip.antiAlias,
                                                          child: Padding(
                                                            padding: const EdgeInsets.all(8.0),
                                                            child: Image.network(
                                                              filteredProducts[i].productPicture,
                                                              fit: BoxFit.cover,
                                                            ),
                                                          ),
                                                        ),
                                                      ],
                                                    ),
                                                    Padding(
                                                      padding: const EdgeInsets.only(top: 6.0, left: 8, right: 8, bottom: 0),
                                                      child: Column(
                                                        crossAxisAlignment: CrossAxisAlignment.start,
                                                        children: [
                                                          /// Product name
                                                          Text(
                                                            filteredProducts[i].productName,
                                                            maxLines: 1,
                                                            overflow: TextOverflow.ellipsis,
                                                            style: theme.textTheme.bodyLarge?.copyWith(
                                                              fontSize: 15,
                                                            ),
                                                          ),
                                                          const SizedBox(height: 4.0),

                                                          /// Price
                                                          Text(
                                                            '$globalCurrency${formatValue(productPriceChecker(product: filteredProducts[i], customerType: selectedCustomerType))}',
                                                            style: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w500),
                                                          ),
                                                        ],
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ).onTap(() {
                                                if (filteredProducts[i].productStock == '0') {
                                                  EasyLoading.showError('Product ${filteredProducts[i].productName} is out of stock');
                                                  return;
                                                }
                                                if (filteredProducts[i].serialNumber.isNotEmpty) {
                                                  showSerialNumberPopUp(productModel: filteredProducts[i]);
                                                } else {
                                                  setState(() {
                                                    AddToCartModel addToCartModel = AddToCartModel(
                                                      productName: filteredProducts[i].productName,
                                                      warehouseName: filteredProducts[i].warehouseName,
                                                      warehouseId: filteredProducts[i].warehouseId,
                                                      productId: filteredProducts[i].productCode,
                                                      productImage: filteredProducts[i].productPicture,
                                                      productPurchasePrice: filteredProducts[i].productPurchasePrice,
                                                      subTotal: productPriceChecker(product: filteredProducts[i], customerType: selectedCustomerType),
                                                      stock: num.parse(filteredProducts[i].productStock),
                                                      productWarranty: filteredProducts[i].warranty,
                                                      serialNumber: [],
                                                      subTaxes: filteredProducts[i].subTaxes,
                                                      excTax: filteredProducts[i].excTax,
                                                      groupTaxName: filteredProducts[i].groupTaxName,
                                                      groupTaxRate: filteredProducts[i].groupTaxRate,
                                                      incTax: filteredProducts[i].incTax,
                                                      margin: filteredProducts[i].margin,
                                                      taxType: filteredProducts[i].taxType,
                                                    );
                                                    if (!uniqueCheck(filteredProducts[i].productCode)) {
                                                      cartList.add(addToCartModel);
                                                      addFocus();
                                                    }
                                                  });
                                                }
                                              });
                                            },
                                          ),
                                        ),
                                      )
                                    : Container(
                                        height: context.height() - 135,
                                        width: double.infinity,
                                        color: Colors.white,
                                        child: SingleChildScrollView(
                                          child: Column(
                                            mainAxisSize: MainAxisSize.min,
                                            children: [
                                              const SizedBox(height: 30),
                                              const Image(
                                                height: 300,
                                                width: 300,
                                                image: AssetImage('images/empty_screen.png'),
                                              ),
                                              const SizedBox(height: 10),
                                              ElevatedButton(
                                                onPressed: () async {
                                                  if (await checkUserRolePermission(type: "product-create")) {
                                                    context.push(
                                                      '/product/add-product',
                                                      extra: {
                                                        'allProductsCodeList': allProductsCodeList,
                                                        'warehouseBasedProductModel': [],
                                                      },
                                                    );
                                                  }
                                                },
                                                child: Text(
                                                  lang.S.of(context).addProduct,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      );
                              }, error: (e, stack) {
                                return Center(
                                  child: Text(e.toString()),
                                );
                              }, loading: () {
                                return const Center(
                                  child: CircularProgressIndicator(),
                                );
                              }),
                            ],
                          ),
                        ),
                      )
                    ])
                  ],
                ),
                const SizedBox(height: 20.0),
              ],
            ),
          ),
        );
      },
    );
  }
}
