import 'dart:async';
import 'dart:convert';

import 'package:firebase_database/firebase_database.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:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:mobile_pos/Provider/category,brans,units_provide.dart';
import 'package:mobile_pos/Provider/product_provider.dart';
import 'package:mobile_pos/Screens/Home/home.dart';
import 'package:mobile_pos/Screens/Products/product_details.dart';
import 'package:mobile_pos/Screens/Products/update_product.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:nb_utils/nb_utils.dart';

import '../../GlobalComponents/button_global.dart';
import '../../const_commas.dart';
import '../../constant.dart';
import '../../currency.dart';
import '../../empty_screen_widget.dart';
import '../../model/product_model.dart';
import '../Warehouse/warehouse_model.dart';
import '../tax report/tax_model.dart';
import 'add_product.dart';

class ProductList extends StatefulWidget {
  const ProductList({super.key});

  @override
  State<ProductList> createState() => _ProductListState();
}

class _ProductListState extends State<ProductList> with TickerProviderStateMixin {
  List<String> productCodeList = [];
  List<String> productNameList = [];
  String searchedProduct = '';
  late String categoryName = category.first;
  int count = 0;

  List<String> get category => ['All', 'Expiring'];
  TabController? tabController;

  // Pagination variables
  final int _pageSize = 10;
  final ScrollController _scrollController = ScrollController();

  // Keep track of pagination for each tab
  final Map<int, List<ProductModel>> _paginatedProducts = {};
  final Map<int, int> _currentPages = {};
  final Map<int, bool> _hasMoreDataByTab = {};
  final Map<int, bool> _isLoadingMoreByTab = {};

  @override
  void initState() {
    super.initState();
    tabController = TabController(length: category.length, vsync: this);

    // Initialize pagination state for each tab
    for (int i = 0; i < category.length; i++) {
      _currentPages[i] = 0;
      _hasMoreDataByTab[i] = true;
      _isLoadingMoreByTab[i] = false;
      _paginatedProducts[i] = [];
    }

    _setupScrollController();
  }

  void _setupScrollController() {
    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        _loadMoreData();
      }
    });
  }

  void _loadMoreData() {
    if (!_isLoadingMoreByTab[_currentTabIndex]! && _hasMoreDataByTab[_currentTabIndex]!) {
      setState(() {
        _isLoadingMoreByTab[_currentTabIndex] = true;
      });

      // Simulate loading delay
      Future.delayed(const Duration(milliseconds: 500), () {
        _currentPages[_currentTabIndex] = _currentPages[_currentTabIndex]! + 1;
        _updatePaginatedData(_currentTabIndex);
      });
    }
  }

  void _updatePaginatedData(int tabIndex) {
    // This will be called from the provider to update paginated data
    setState(() {
      _isLoadingMoreByTab[tabIndex] = false;
    });
  }

  void _resetPagination(int tabIndex) {
    _currentPages[tabIndex] = 0;
    _hasMoreDataByTab[tabIndex] = true;
    _paginatedProducts[tabIndex]!.clear();
  }

  int get _currentTabIndex => tabController?.index ?? 0;

  // Your existing deleteProduct method remains the same
  void deleteProduct(
      {required String productCode,
      required WidgetRef updateProduct,
      required BuildContext context}) async {
    // if (finalUserRoleModel.productDelete == false) {
    //   toast(lang.S.of(context).sorryYouHaveNoPermissionToAccessThisService);
    //   return;
    // }
    EasyLoading.show(status: '${lang.S.of(context).deleting}..');
    String customerKey = '';
    await FirebaseDatabase.instance
        .ref(await getUserID())
        .child('Products')
        .orderByKey()
        .get()
        .then((value) {
      for (var element in value.children) {
        var data = jsonDecode(jsonEncode(element.value));
        if (data['productCode'].toString() == productCode) {
          customerKey = element.key.toString();
        }
      }
    });
    DatabaseReference ref =
        FirebaseDatabase.instance.ref("${await getUserID()}/Products/$customerKey");
    await ref.remove();
    updateProduct.refresh(categoryProvider);
    updateProduct.refresh(productProvider);
    Navigator.pop(context);
    EasyLoading.showSuccess(lang.S.of(context).done);
  }

  int currentTabIndex = 0;
  int i = 0;

  @override
  Widget build(BuildContext context) {
    List<WarehouseBasedProductModel> warehouseBasedProductModel = [];
    List<String> allWarehouseId = [];

    return Consumer(builder: (context, ref, __) {
      final groupTax = ref.watch(groupTaxProvider);
      final providerData = ref.watch(productProvider);
      final categoryData = ref.watch(categoryProvider);

      return categoryData.when(data: (categoryList) {
        for (int i = 0; i < categoryList.length; i++) {
          category.contains(categoryList[i].categoryName)
              ? null
              : category.add(categoryList[i].categoryName);
        }

        i == 0 ? tabController = TabController(length: category.length, vsync: this) : null;
        i++;

        return DefaultTabController(
          initialIndex: 0,
          length: category.length,
          child: Scaffold(
            backgroundColor: kMainColor,
            appBar: AppBar(
              backgroundColor: kMainColor,
              elevation: 0,
              iconTheme: const IconThemeData(color: Colors.white),
              leading: const Icon(
                Icons.arrow_back,
                color: Colors.white,
              ).onTap(() async {
                await Future.delayed(const Duration(microseconds: 100))
                    .then((value) => const Home().launch(context));
              }),
              title: Text(
                lang.S.of(context).productList,
                style: GoogleFonts.poppins(
                  color: Colors.white,
                ),
              ),
              centerTitle: true,
            ),
            body: WillPopScope(
              onWillPop: () async {
                await Future.delayed(const Duration(microseconds: 100)).then((value) {
                  if (mounted) {
                    const Home().launch(context);
                    return true;
                  } else {
                    return false;
                  }
                });
                return false;
              },
              child: Container(
                alignment: Alignment.topCenter,
                decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                        topRight: Radius.circular(30), topLeft: Radius.circular(30))),
                child: Column(
                  children: [
                    const SizedBox(height: 10.0),
                    TabBar(
                      controller: tabController,
                      padding: EdgeInsets.zero,
                      isScrollable: true,
                      labelColor: kMainColor,
                      unselectedLabelColor: kGreyTextColor,
                      indicatorColor: kMainColor,
                      indicatorSize: TabBarIndicatorSize.tab,
                      tabAlignment: TabAlignment.start,
                      indicator: UnderlineTabIndicator(
                        borderSide: const BorderSide(color: kMainColor, width: 4),
                        borderRadius: BorderRadius.only(
                          topLeft: radiusCircular(6.0),
                          topRight: radiusCircular(6.0),
                        ),
                      ),
                      tabs: category.map((String tab) {
                        return Tab(text: tab);
                      }).toList(),
                    ),
                    const SizedBox(height: 10.0),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 0.0),
                      child: AppTextField(
                        textFieldType: TextFieldType.NAME,
                        onChanged: (value) {
                          setState(() {
                            searchedProduct = value;
                            // Reset pagination when search changes
                            for (int i = 0; i < category.length; i++) {
                              _resetPagination(i);
                            }
                          });
                        },
                        decoration: InputDecoration(
                            contentPadding: const EdgeInsets.only(left: 8.0, right: 8.0),
                            floatingLabelBehavior: FloatingLabelBehavior.never,
                            labelText: lang.S.of(context).productName,
                            hintText: lang.S.of(context).enterProductName,
                            border: const OutlineInputBorder(),
                            prefixIcon: const Icon(Icons.search)),
                      ),
                    ),
                    Expanded(
                      child: TabBarView(
                        controller: tabController,
                        children: List.generate(
                          category.length,
                          (tabIndex) => _buildProductListForTab(
                              tabIndex, ref, providerData, warehouseBasedProductModel, groupTax),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            bottomNavigationBar: Container(
              color: Colors.white,
              child: ButtonGlobal(
                iconWidget: Icons.add,
                buttontext: lang.S.of(context).addNewProduct,
                iconColor: Colors.white,
                buttonDecoration: kButtonDecoration.copyWith(
                    color: kMainColor, borderRadius: const BorderRadius.all(Radius.circular(30))),
                onPressed: () async {
                  if (await checkUserRolePermission(type: "product-create")) {
                    bool? isAdded = await AddProduct(
                      productNameList: productNameList,
                      productCodeList: productCodeList,
                      warehouseBasedProductModel: warehouseBasedProductModel,
                    ).launch(context);

                    if (isAdded ?? false) {
                      ref.refresh(categoryProvider);
                      ref.refresh(brandsProvider);
                      ref.refresh(productProvider);
                    }
                  }
                },
              ),
            ),
          ),
        );
      }, error: (e, stack) {
        return Scaffold(
          body: Center(
            child: Text(e.toString()),
          ),
        );
      }, loading: () {
        return const Scaffold(
          body: Center(
            child: CircularProgressIndicator(),
          ),
        );
      });
    });
  }

  Widget _buildProductListForTab(
    int tabIndex,
    WidgetRef ref,
    AsyncValue<List<ProductModel>> providerData,
    List<WarehouseBasedProductModel> warehouseBasedProductModel,
    AsyncValue<List<GroupTaxModel>> groupTax,
  ) {
    return providerData.when(
      data: (allProducts) {
        // Filter products based on tab and search
        final reversedProducts = allProducts.reversed.toList();
        List<ProductModel> filteredProducts =
            _filterProductsForTab(tabIndex, reversedProducts, searchedProduct);

        // Calculate pagination
        int startIndex = _currentPages[tabIndex]! * _pageSize;
        int endIndex = startIndex + _pageSize;

        if (endIndex > filteredProducts.length) {
          endIndex = filteredProducts.length;
        }

        List<ProductModel> productsToShow = filteredProducts.sublist(0, endIndex);

        // Update hasMoreData flag
        _hasMoreDataByTab[tabIndex] = endIndex < filteredProducts.length;

        return NotificationListener<ScrollNotification>(
          onNotification: (ScrollNotification scrollInfo) {
            if (scrollInfo.metrics.pixels == scrollInfo.metrics.maxScrollExtent &&
                _hasMoreDataByTab[tabIndex]! &&
                !_isLoadingMoreByTab[tabIndex]!) {
              _loadMoreDataForTab(tabIndex);
            }
            return false;
          },
          child: Column(
            children: [
              Expanded(
                child: productsToShow.isNotEmpty
                    ? ListView.builder(
                        controller: _scrollController,
                        itemCount:
                            productsToShow.length + (_isLoadingMoreByTab[tabIndex]! ? 1 : 0),
                        itemBuilder: (_, index) {
                          if (index == productsToShow.length) {
                            return _buildLoadingIndicator();
                          }

                          final product = productsToShow[index];
                          productCodeList
                              .add(product.productCode.replaceAll(' ', '').toLowerCase());
                          productNameList
                              .add(product.productName.replaceAll(' ', '').toLowerCase());

                          return Column(
                            children: [
                              ListTile(
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => ProductDetails(
                                        productModel: product,
                                        canUpdate: finalUserRoleModel.productUpdate ?? isSubUser,
                                      ),
                                    ),
                                  );
                                },
                                leading: Container(
                                  height: 50,
                                  width: 50,
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    border: Border.all(color: kBorderColorTextField),
                                    image: DecorationImage(
                                      fit: BoxFit.cover,
                                      image: NetworkImage(product.productPicture),
                                    ),
                                  ),
                                ),
                                title: Text(product.productName,
                                    maxLines: 2, overflow: TextOverflow.ellipsis),
                                subtitle: Text(
                                    "${lang.S.of(context).stocks} : ${myFormat.format(num.tryParse(product.productStock) ?? 0)} (${product.warehouseName})"),
                                trailing: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.end,
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        Text(
                                          "$currency ${myFormat.format(double.tryParse(product.productSalePrice) ?? 0)}",
                                          style: const TextStyle(fontSize: 18),
                                        ),
                                        Visibility(
                                          visible: (category[tabIndex] == 'Expiring' &&
                                              product.expiringDate != null),
                                          child: Text(
                                            (DateTime.tryParse(product.expiringDate ?? '') ??
                                                        DateTime.now())
                                                    .isBefore(DateTime(DateTime.now().year,
                                                        DateTime.now().month, DateTime.now().day))
                                                ? lang.S.of(context).expired
                                                : "${lang.S.of(context).willExpireAt} ${DateFormat.yMMMd().format(DateTime.tryParse(product.expiringDate ?? '') ?? DateTime.now())}",
                                            style:
                                                const TextStyle(fontSize: 10, color: Colors.red),
                                            textAlign: TextAlign.center,
                                          ),
                                        ),
                                      ],
                                    ),
                                    SizedBox(
                                      width: 30,
                                      child: PopupMenuButton(
                                        padding: EdgeInsets.zero,
                                        itemBuilder: (BuildContext bc) => [
                                          PopupMenuItem(
                                            child: InkWell(
                                              onTap: () async {
                                                if (await checkUserRolePermission(
                                                    type: "product-update")) {
                                                  UpdateProduct(
                                                    productModel: product,
                                                    productCodeList: productCodeList,
                                                    productNameList: productNameList,
                                                    groupTaxModel: groupTax.value ?? [],
                                                  ).launch(context);
                                                }
                                              },
                                              child: Row(
                                                children: [
                                                  const Icon(FeatherIcons.edit3,
                                                      size: 18.0, color: Colors.black),
                                                  const SizedBox(width: 4.0),
                                                  Text(
                                                    lang.S.of(context).edit,
                                                    style: const TextStyle(color: Colors.black),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                          PopupMenuItem(
                                            child: GestureDetector(
                                              onTap: () async {
                                                if (await checkUserRolePermission(
                                                    type: "product-update")) {
                                                  addStockPopUp(
                                                      context, productsToShow, index, ref);
                                                }
                                              },
                                              child: Row(
                                                children: [
                                                  const Icon(Icons.add,
                                                      size: 18.0, color: Colors.black),
                                                  const SizedBox(width: 4.0),
                                                  Text(
                                                    lang.S.of(context).increaseStock,
                                                    style: const TextStyle(color: Colors.black),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                          PopupMenuItem(
                                            child: GestureDetector(
                                              onTap: () async {
                                                if (await checkUserRolePermission(
                                                    type: "product-delete")) {
                                                  deleteProduct(
                                                      productCode: product.productCode,
                                                      updateProduct: ref,
                                                      context: bc);
                                                }
                                              },
                                              child: Row(
                                                children: [
                                                  const Icon(Icons.delete,
                                                      size: 18.0, color: Colors.black),
                                                  const SizedBox(width: 4.0),
                                                  Text(
                                                    lang.S.of(context).delete,
                                                    style: const TextStyle(color: Colors.black),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                        ],
                                        onSelected: (value) {
                                          Navigator.pushNamed(context, '$value');
                                        },
                                        child: Center(
                                          child: Container(
                                            height: 18,
                                            width: 18,
                                            alignment: Alignment.centerRight,
                                            child: const Icon(
                                              Icons.more_vert_sharp,
                                              size: 20,
                                              color: Colors.black,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              Divider(
                                height: 1,
                                thickness: 1.0,
                                color: kBorderColor.withValues(alpha: 0.3),
                              )
                            ],
                          );
                        },
                      )
                    : const Center(
                        child: Padding(
                          padding: EdgeInsets.only(top: 60),
                          child: EmptyScreenWidget(),
                        ),
                      ),
              ),
            ],
          ),
        );
      },
      error: (e, stack) {
        return Center(child: Text('Error: ${e.toString()}'));
      },
      loading: () {
        return const Center(child: CircularProgressIndicator());
      },
    );
  }

  List<ProductModel> _filterProductsForTab(
      int tabIndex, List<ProductModel> allProducts, String searchQuery) {
    List<ProductModel> filteredProducts = [];

    for (var element in allProducts) {
      productNameList.add(element.productName.removeAllWhiteSpace().toLowerCase());
      productCodeList.add(element.productCode.removeAllWhiteSpace().toLowerCase());

      bool matchesSearch = searchQuery.isEmpty ||
          element.productName
              .removeAllWhiteSpace()
              .toLowerCase()
              .contains(searchQuery.toLowerCase()) ||
          element.productName.contains(searchQuery);

      bool matchesCategory = false;

      if (category[tabIndex] == 'All') {
        matchesCategory = true;
      } else if (category[tabIndex] == 'Expiring') {
        matchesCategory = element.expiringDate != null &&
            ((DateTime.tryParse(element.expiringDate ?? '') ?? DateTime.now())
                .isBefore(DateTime.now().add(const Duration(days: 7))));
      } else {
        matchesCategory = element.productCategory == category[tabIndex];
      }

      if (matchesSearch && matchesCategory) {
        filteredProducts.add(element);
      }
    }

    return filteredProducts;
  }

  void _loadMoreDataForTab(int tabIndex) {
    if (!_isLoadingMoreByTab[tabIndex]! && _hasMoreDataByTab[tabIndex]!) {
      setState(() {
        _isLoadingMoreByTab[tabIndex] = true;
      });

      // Simulate loading delay
      Future.delayed(const Duration(milliseconds: 500), () {
        setState(() {
          _currentPages[tabIndex] = _currentPages[tabIndex]! + 1;
          _isLoadingMoreByTab[tabIndex] = false;
        });
      });
    }
  }

  Widget _buildLoadingIndicator() {
    return const Padding(
      padding: EdgeInsets.all(16.0),
      child: Center(
        child: CircularProgressIndicator(),
      ),
    );
  }

  // Your existing addStockPopUp method remains the same
  Future<dynamic> addStockPopUp(
      BuildContext context1, List<ProductModel> products, int i, WidgetRef pref) {
    final ref = FirebaseDatabase.instance.ref(constUserId).child('Products');
    // String productKey = '';
    // ref.keepSynced(true);
    //
    // ref.orderByKey().get().then((value) {
    //   for (var element in value.children) {
    //     var data = jsonDecode(jsonEncode(element.value));
    //     if (data['productCode'].toString() == products[i].productCode) {
    //       productKey = element.key.toString();
    //     }
    //   }
    // });
    return showDialog(
        context: context,
        builder: (_) {
          ProductModel product = products[i];
          TextEditingController stockController = TextEditingController(text: '1');
          TextEditingController salePriceController =
              TextEditingController(text: product.productSalePrice);
          TextEditingController purchaseController =
              TextEditingController(text: product.productPurchasePrice);
          TextEditingController wholeSellerController =
              TextEditingController(text: product.productWholeSalePrice);
          TextEditingController dealerController =
              TextEditingController(text: product.productDealerPrice);
          return AlertDialog(
              content: SizedBox(
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(bottom: 10),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          lang.S.of(context).increaseStock,
                          //'Increase Stock',
                          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                        ),
                        GestureDetector(
                            onTap: () {
                              Navigator.pop(context);
                            },
                            child: const Icon(
                              Icons.cancel,
                              color: kMainColor,
                            )),
                      ],
                    ),
                  ),
                  Container(
                    height: 1,
                    width: double.infinity,
                    color: Colors.grey,
                  ),
                  const SizedBox(height: 10),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            products[i].productName,
                            style: const TextStyle(fontSize: 16),
                          ),
                          Text(
                            products[i].brandName,
                            style: const TextStyle(
                              fontSize: 16,
                              color: Colors.grey,
                            ),
                          ),
                        ],
                      ),
                      Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          Text(
                            lang.S.of(context).stocks,
                            style: const TextStyle(fontSize: 16),
                          ),
                          Text(
                            product.productStock,
                            style: const TextStyle(
                              fontSize: 16,
                              color: Colors.grey,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                  const SizedBox(height: 20),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Expanded(
                        child: AppTextField(
                          controller: stockController,
                          textFieldType: TextFieldType.NUMBER,
                          decoration: InputDecoration(
                            floatingLabelBehavior: FloatingLabelBehavior.always,
                            labelText: lang.S.of(context).quantity,
                            border: const OutlineInputBorder(),
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 20),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Expanded(
                        child: AppTextField(
                          controller: purchaseController,
                          keyboardType: TextInputType.number,
                          textFieldType: TextFieldType.NAME,
                          decoration: InputDecoration(
                            floatingLabelBehavior: FloatingLabelBehavior.always,
                            labelText: lang.S.of(context).purchasePrice,
                            border: const OutlineInputBorder(),
                          ),
                        ),
                      ),
                      const SizedBox(width: 10),
                      Expanded(
                        child: AppTextField(
                          controller: salePriceController,
                          keyboardType: TextInputType.number,
                          textFieldType: TextFieldType.NAME,
                          decoration: InputDecoration(
                            floatingLabelBehavior: FloatingLabelBehavior.always,
                            labelText: lang.S.of(context).salePrice,
                            border: const OutlineInputBorder(),
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 20),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Expanded(
                        child: AppTextField(
                          controller: wholeSellerController,
                          keyboardType: TextInputType.number,
                          textFieldType: TextFieldType.NAME,
                          decoration: InputDecoration(
                            floatingLabelBehavior: FloatingLabelBehavior.always,
                            labelText: lang.S.of(context).wholeSalePrice,
                            border: const OutlineInputBorder(),
                          ),
                        ),
                      ),
                      const SizedBox(width: 10),
                      Expanded(
                        child: AppTextField(
                          controller: dealerController,
                          keyboardType: TextInputType.number,
                          textFieldType: TextFieldType.NAME,
                          decoration: InputDecoration(
                            floatingLabelBehavior: FloatingLabelBehavior.always,
                            labelText: lang.S.of(context).dealerPrice,
                            border: const OutlineInputBorder(),
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 20),
                  GestureDetector(
                    onTap: () async {
                      if (product.productStock != '0') {
                        DatabaseReference ref = FirebaseDatabase.instance
                            .ref("$constUserId/Products/${product.productKey}");

                        ref.keepSynced(true);
                        num updatedStock = (num.tryParse(product.productStock) ?? 0) +
                            (num.tryParse(stockController.text) ?? 0);
                        await ref.update({
                          'productStock': updatedStock.toString(),
                          'productSalePrice': salePriceController.text,
                          'productPurchasePrice': purchaseController.text,
                          'productWholeSalePrice': wholeSellerController.text,
                          'productDealerPrice': dealerController.text,
                        });
                        EasyLoading.showSuccess(lang.S.of(context).done);

                        pref.refresh(categoryProvider);
                        pref.refresh(productProvider);
                        Navigator.pop(context);
                        Navigator.pop(context1);
                      } else {
                        // EasyLoading.showError('Please add quantity');
                        EasyLoading.showError(lang.S.of(context).pleaseAddQuantity);
                      }
                    },
                    child: Container(
                      height: 60,
                      width: context.width(),
                      decoration: const BoxDecoration(
                          color: kMainColor, borderRadius: BorderRadius.all(Radius.circular(30))),
                      child: Center(
                        child: Text(
                          lang.S.of(context).save,
                          style: const TextStyle(fontSize: 18, color: Colors.white),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ));
        });
  }
}
