import 'dart:convert';
import 'dart:math';

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:go_router/go_router.dart';
import 'package:iconly/iconly.dart';
import 'package:intl/intl.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/tax%20rates/tax_model.dart';
import 'package:salespro_admin/commas.dart';
import 'package:salespro_admin/generated/l10n.dart' as lang;
import 'package:salespro_admin/model/product_model.dart';

import '../../Provider/product_provider.dart';
import '../../const.dart';
import '../Widgets/Constant Data/constant.dart';
import '../Widgets/Constant Data/export_button.dart';
import '../currency/currency_provider.dart';

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

  @override
  State<ProductExpiredList> createState() => _ProductExpiredListState();
}

class _ProductExpiredListState extends State<ProductExpiredList> {
  int itemsPerPage = 10;
  String searchItem = '';
  String isSelected = 'Product List';
  int _currentPage = 1;
  final int _productsPerPage = 10;

  List<String> title = ['Product List', 'Expired List'];
  final _horizontalController = ScrollController();

  Future<void> productStockEditPopUp({required ProductModel product, required BuildContext popUp, required WidgetRef pref}) async {
    TextEditingController stockController = TextEditingController(text: '0');
    TextEditingController saleController = TextEditingController(text: myFormat.format(double.tryParse(product.productSalePrice) ?? 0));
    TextEditingController purchaseController = TextEditingController(text: myFormat.format(double.tryParse(product.productPurchasePrice) ?? 0));
    TextEditingController wholeSeller = TextEditingController(text: myFormat.format(double.tryParse(product.productWholeSalePrice) ?? 0));
    TextEditingController dealer = TextEditingController(text: myFormat.format(double.tryParse(product.productDealerPrice) ?? 0));

    String stock = '0';
    String productSalePrice = product.productSalePrice;
    String productPurchasePrice = product.productPurchasePrice;
    String productWholePrice = product.productWholeSalePrice;
    String productDealerPrice = product.productDealerPrice;

    GlobalKey<FormState> priceKey = GlobalKey<FormState>();
    bool validateAndSave() {
      final form = priceKey.currentState;
      if (form!.validate()) {
        form.save();
        return true;
      }
      return false;
    }

    await showDialog(
      barrierDismissible: false,
      context: popUp,
      builder: (BuildContext context) {
        final theme = Theme.of(context);
        return StatefulBuilder(
          builder: (context1, setState1) {
            return Dialog(
              surfaceTintColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5.0),
              ),
              child: SizedBox(
                width: 500,
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Flexible(
                              child: Text(
                                "${product.productName} (${product.productStock})",
                                style: theme.textTheme.titleLarge?.copyWith(
                                  fontWeight: FontWeight.w600,
                                ),
                                overflow: TextOverflow.ellipsis,
                                maxLines: 2,
                              ),
                            ),
                            IconButton(
                              onPressed: () => GoRouter.of(context).pop(),
                              icon: Icon(
                                FeatherIcons.x,
                                color: kGreyTextColor,
                                size: 25.0,
                              ),
                            )
                          ],
                        ),
                      ),
                      const Divider(
                        thickness: 1.0,
                        color: kNeutral300,
                        height: 1,
                      ),
                      const SizedBox(height: 10.0),
                      Form(
                        key: priceKey,
                        child: Column(
                          children: [
                            Padding(
                              padding: const EdgeInsets.all(10.0),
                              child: TextFormField(
                                controller: stockController,
                                onChanged: (value) {
                                  stock = value.replaceAll(',', '');
                                  var formattedText = myFormat.format(num.parse(stock));
                                  stockController.value = stockController.value.copyWith(
                                    text: formattedText,
                                    selection: TextSelection.collapsed(offset: formattedText.length),
                                  );
                                },
                                validator: (value) {
                                  if (stock.isEmptyOrNull) {
                                    return 'Please enter Stock';
                                  } else if (double.tryParse(stock) == null && stock.isEmptyOrNull) {
                                    return 'Enter Stock in number.';
                                  } else {
                                    return null;
                                  }
                                },
                                showCursor: true,
                                cursorColor: kTitleColor,
                                decoration: InputDecoration(
                                  labelText: lang.S.of(context).productStock,
                                  hintText: lang.S.of(context).pleaseEnterProductStock,
                                ),
                              ),
                            ),
                            ResponsiveGridRow(children: [
                              ResponsiveGridCol(
                                  md: 6,
                                  lg: 6,
                                  xs: 12,
                                  child: Padding(
                                    padding: const EdgeInsets.all(10.0),
                                    child: TextFormField(
                                      controller: purchaseController,
                                      onChanged: (value) {
                                        productPurchasePrice = value.replaceAll(',', '');
                                        var formattedText = myFormat.format(num.parse(productPurchasePrice));
                                        purchaseController.value = purchaseController.value.copyWith(
                                          text: formattedText,
                                          selection: TextSelection.collapsed(offset: formattedText.length),
                                        );
                                      },
                                      validator: (value) {
                                        if (productPurchasePrice.isEmptyOrNull) {
                                          return 'Please enter Purchase Price';
                                        } else if (double.tryParse(productPurchasePrice) == null && productPurchasePrice.isEmptyOrNull) {
                                          return 'Enter Price in number.';
                                        } else {
                                          return null;
                                        }
                                      },
                                      showCursor: true,
                                      cursorColor: kTitleColor,
                                      decoration: InputDecoration(
                                        labelText: lang.S.of(context).purchasePrice,
                                        hintText: lang.S.of(context).enterPurchasePrice,
                                      ),
                                    ),
                                  )),
                              ResponsiveGridCol(
                                  md: 6,
                                  lg: 6,
                                  xs: 12,
                                  child: Padding(
                                    padding: const EdgeInsets.all(10.0),
                                    child: TextFormField(
                                      controller: saleController,
                                      onChanged: (value) {
                                        productSalePrice = value.replaceAll(',', '');
                                        var formattedText = myFormat.format(num.parse(productSalePrice));
                                        saleController.value = saleController.value.copyWith(
                                          text: formattedText,
                                          selection: TextSelection.collapsed(offset: formattedText.length),
                                        );
                                      },
                                      validator: (value) {
                                        if (productSalePrice.isEmptyOrNull) {
                                          return 'Please enter Sale Price';
                                        } else if (double.tryParse(productSalePrice) == null && productSalePrice.isEmptyOrNull) {
                                          return 'Enter Price in number.';
                                        } else {
                                          return null;
                                        }
                                      },
                                      showCursor: true,
                                      cursorColor: kTitleColor,
                                      decoration: InputDecoration(
                                        labelText: lang.S.of(context).salePrices,
                                        hintText: lang.S.of(context).enterSalePrice,
                                      ),
                                    ),
                                  ))
                            ]),
                            ResponsiveGridRow(children: [
                              ResponsiveGridCol(
                                  md: 6,
                                  lg: 6,
                                  xs: 123,
                                  child: Padding(
                                    padding: const EdgeInsets.all(10.0),
                                    child: TextFormField(
                                      controller: dealer,
                                      onChanged: (value) {
                                        productDealerPrice = value.replaceAll(',', '');
                                        var formattedText = myFormat.format(num.parse(productDealerPrice));
                                        dealer.value = dealer.value.copyWith(
                                          text: formattedText,
                                          selection: TextSelection.collapsed(offset: formattedText.length),
                                        );
                                      },
                                      validator: (value) {
                                        return null;
                                      },
                                      showCursor: true,
                                      cursorColor: kTitleColor,
                                      decoration: InputDecoration(
                                        labelText: lang.S.of(context).dealerPrice,
                                        hintText: lang.S.of(context).enterDealePrice,
                                      ),
                                    ),
                                  )),
                              ResponsiveGridCol(
                                  md: 6,
                                  lg: 6,
                                  xs: 12,
                                  child: Padding(
                                    padding: const EdgeInsets.all(10.0),
                                    child: TextFormField(
                                      controller: wholeSeller,
                                      onChanged: (value) {
                                        productWholePrice = value.replaceAll(',', '');
                                        var formattedText = myFormat.format(num.parse(productWholePrice));
                                        wholeSeller.value = wholeSeller.value.copyWith(
                                          text: formattedText,
                                          selection: TextSelection.collapsed(offset: formattedText.length),
                                        );
                                      },
                                      validator: (value) {
                                        return null;
                                      },
                                      showCursor: true,
                                      cursorColor: kTitleColor,
                                      decoration: InputDecoration(
                                        labelText: lang.S.of(context).wholeSaleprice,
                                        hintText: lang.S.of(context).enterPrice,
                                      ),
                                    ),
                                  ))
                            ]),
                          ],
                        ),
                      ),
                      const SizedBox(height: 6),
                      ResponsiveGridRow(children: [
                        ResponsiveGridCol(
                            md: 6,
                            lg: 6,
                            xs: 12,
                            child: Padding(
                              padding: const EdgeInsets.all(10.0),
                              child: ElevatedButton(
                                  style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
                                  onPressed: () => GoRouter.of(context).pop(),
                                  child: Text(
                                    lang.S.of(context).cancel,
                                  )),
                            )),
                        ResponsiveGridCol(
                            md: 6,
                            lg: 6,
                            xs: 12,
                            child: Padding(
                              padding: const EdgeInsets.all(10.0),
                              child: ElevatedButton(
                                onPressed: () async {
                                  if (finalUserRoleModel.productUpdate == false) {
                                    EasyLoading.showError(userPermissionErrorText);
                                    return;
                                  }
                                  if (validateAndSave()) {
                                    final userID = await getUserID();
                                    final ref = FirebaseDatabase.instance.ref(userID).child('Products');
                                    String productKey = '';

                                    await ref.orderByKey().get().then((value) {
                                      for (var element in value.children) {
                                        var data = jsonDecode(jsonEncode(element.value));
                                        if (data['productCode'].toString() == product.productCode) {
                                          productKey = element.key.toString();
                                        }
                                      }
                                    });

                                    await ref.child(productKey).update({
                                      'productStock': ((num.tryParse(stock) ?? 0) + (num.tryParse(product.productStock) ?? 0)).toString(),
                                      // 'productStock': stockController.text,
                                      'productSalePrice': productSalePrice,
                                      'productPurchasePrice': productPurchasePrice,
                                      'productWholeSalePrice': productWholePrice,
                                      'productDealerPrice': productDealerPrice,
                                    });
                                    EasyLoading.showSuccess('Done');
                                    pref.refresh(productProvider);
                                    GoRouter.of(context).pop();
                                    // Navigator.pop(popUp);
                                  }
                                },
                                child: Text(
                                  lang.S.of(context).submit,
                                ),
                              ),
                            )),
                      ]),
                      const SizedBox(height: 6),
                    ],
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }

  void deleteProduct({
    required String productCode,
    required WidgetRef updateProduct,
    required BuildContext context,
  }) async {
    EasyLoading.show(status: 'Deleting..');

    try {
      String userId = await getUserID(); // Get User ID first
      DatabaseReference productRef = FirebaseDatabase.instance.ref('$userId/Products');

      DataSnapshot snapshot = await productRef.orderByKey().get();

      String customerKey = '';

      for (var element in snapshot.children) {
        var data = jsonDecode(jsonEncode(element.value));

        if (data['productCode'].toString() == productCode) {
          customerKey = element.key.toString();
          break; // Exit loop as soon as the key is found
        }
      }

      if (customerKey.isNotEmpty) {
        await FirebaseDatabase.instance.ref('$userId/Products/$customerKey').remove();
        updateProduct.refresh(productProvider); // Refresh UI

        EasyLoading.showSuccess('Product Deleted');
      } else {
        EasyLoading.showError('Product Not Found');
      }
    } catch (e) {
      EasyLoading.showError('Error: $e');
    }
  }

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

  // Keep all your existing methods (productStockEditPopUp, deleteProduct, etc.)

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    final currencyProvider = pro.Provider.of<CurrencyProvider>(context);
    final globalCurrency = currencyProvider.currency ?? '\$';
    final theme = Theme.of(context);

    return Scaffold(
      backgroundColor: kDarkWhite,
      body: Consumer(
        builder: (_, ref, watch) {
          AsyncValue<List<ProductModel>> productList = ref.watch(productProvider);
          final groupTax = ref.watch(groupTaxProvider);

          return productList.when(data: (allProducts) {
            List<ProductModel> expiredProducts = [];
            List<String> allProductsNameList = [];
            List<String> allProductsCodeList = [];

            for (var element in allProducts) {
              allProductsNameList.add(element.productName.removeAllWhiteSpace().toLowerCase());
              allProductsCodeList.add(element.productCode.removeAllWhiteSpace().toLowerCase());

              // Only add expired or soon-to-expire products (within 7 days)
              if (element.expiringDate != null && (DateTime.tryParse(element.expiringDate ?? '') ?? DateTime.now()).isBefore(DateTime.now().add(const Duration(days: 7)))) {
                expiredProducts.add(element);
              }
            }

            // Apply search filter if needed
            if (searchItem.isNotEmpty) {
              expiredProducts = expiredProducts.where((product) => product.productName.removeAllWhiteSpace().toLowerCase().contains(searchItem.toLowerCase()) || product.productName.contains(searchItem)).toList();
            }

            return SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Container(
                decoration: const BoxDecoration(color: kDarkWhite),
                child: Container(
                  decoration: BoxDecoration(borderRadius: BorderRadius.circular(8.0), color: kWhite),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 13),
                        child: Text(
                          'Expired Products List',
                          style: theme.textTheme.titleLarge?.copyWith(
                            fontWeight: FontWeight.w700,
                          ),
                        ),
                      ),
                      const Divider(height: 1, thickness: 1.0, color: kDividerColor),
                      const SizedBox(height: 16),

                      ///________Search and filter controls_______________________________________
                      ResponsiveGridRow(rowSegments: 100, children: [
                        ResponsiveGridCol(
                          xs: screenWidth < 360
                              ? 50
                              : screenWidth > 430
                                  ? 33
                                  : 40,
                          md: screenWidth < 768
                              ? 24
                              : screenWidth < 950
                                  ? 20
                                  : 15,
                          lg: screenWidth < 1700 ? 15 : 10,
                          child: Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: Container(
                              alignment: Alignment.center,
                              height: 48,
                              padding: const EdgeInsets.all(10),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(8.0),
                                border: Border.all(color: kNeutral300),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Flexible(child: Text('Show-', style: theme.textTheme.bodyLarge)),
                                  DropdownButton<int>(
                                    isDense: true,
                                    padding: EdgeInsets.zero,
                                    underline: const SizedBox(),
                                    value: itemsPerPage,
                                    icon: const Icon(Icons.keyboard_arrow_down, color: Colors.black),
                                    items: [10, 20, 50, 100, -1].map<DropdownMenuItem<int>>((int value) {
                                      return DropdownMenuItem<int>(
                                        value: value,
                                        child: Text(
                                          value == -1 ? "All" : value.toString(),
                                          style: theme.textTheme.bodyLarge,
                                        ),
                                      );
                                    }).toList(),
                                    onChanged: (int? newValue) {
                                      setState(() {
                                        itemsPerPage = newValue ?? 10;
                                        _currentPage = 1;
                                      });
                                    },
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                        ResponsiveGridCol(
                          xs: 100,
                          md: 60,
                          lg: 35,
                          child: Padding(
                            padding: const EdgeInsets.all(10),
                            child: AppTextField(
                              showCursor: true,
                              cursorColor: kTitleColor,
                              onChanged: (value) {
                                setState(() {
                                  searchItem = value;
                                  _currentPage = 1;
                                });
                              },
                              textFieldType: TextFieldType.NAME,
                              decoration: InputDecoration(
                                hintText: 'Search by product name',
                                suffixIcon: const Icon(FeatherIcons.search, color: kNeutral700),
                              ),
                            ),
                          ),
                        )
                      ]),

                      ///_______Expired_products_list______________________________________________________
                      const SizedBox(height: 20.0),

                      expiredProducts.isNotEmpty
                          ? Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Scrollbar(
                                  thickness: 8.0,
                                  thumbVisibility: true,
                                  controller: _horizontalController,
                                  radius: const Radius.circular(5),
                                  child: LayoutBuilder(
                                    builder: (BuildContext context, BoxConstraints constraints) {
                                      return SingleChildScrollView(
                                        scrollDirection: Axis.horizontal,
                                        controller: _horizontalController,
                                        child: ConstrainedBox(
                                          constraints: BoxConstraints(
                                            minWidth: constraints.maxWidth,
                                            minHeight: MediaQuery.of(context).size.height - 370,
                                          ),
                                          child: Theme(
                                            data: ThemeData(
                                              dividerColor: kNeutral300,
                                              textTheme: theme.textTheme,
                                            ),
                                            child: DataTable(
                                              border: const TableBorder(
                                                horizontalInside: BorderSide(
                                                  width: 1,
                                                  color: kNeutral300,
                                                ),
                                              ),
                                              dataRowColor: const WidgetStatePropertyAll(Colors.white),
                                              headingRowColor: WidgetStateProperty.all(const Color(0xFFF8F3FF)),
                                              showBottomBorder: true,
                                              dividerThickness: 1.0,
                                              headingTextStyle: theme.textTheme.titleMedium,
                                              dataTextStyle: theme.textTheme.bodyLarge,
                                              columns: const [
                                                DataColumn(label: Text('S.L')),
                                                DataColumn(label: Text('Image')),
                                                DataColumn(label: Text('Product Name')),
                                                DataColumn(label: Text('Category')),
                                                DataColumn(label: Text('Price')),
                                                DataColumn(label: Text('Stock')),
                                                DataColumn(label: Text('Expiry Date')),
                                                DataColumn(label: Text('Status')),
                                                DataColumn(label: Icon(Icons.settings)),
                                              ],
                                              rows: List.generate(
                                                itemsPerPage == -1
                                                    ? expiredProducts.length
                                                    : (_currentPage - 1) * itemsPerPage < expiredProducts.length
                                                        ? (_currentPage * itemsPerPage <= expiredProducts.length ? itemsPerPage : expiredProducts.length - (_currentPage - 1) * itemsPerPage)
                                                        : 0,
                                                (index) {
                                                  final dataIndex = (_currentPage - 1) * itemsPerPage + index;
                                                  final product = expiredProducts[dataIndex];
                                                  final expiryDate = DateTime.tryParse(product.expiringDate ?? '') ?? DateTime.now();
                                                  final isExpired = expiryDate.isBefore(DateTime.now());

                                                  return DataRow(
                                                    cells: [
                                                      DataCell(Text('${dataIndex + 1}')),
                                                      DataCell(
                                                        Container(
                                                          height: 40,
                                                          width: 40,
                                                          decoration: BoxDecoration(
                                                            shape: BoxShape.circle,
                                                            border: Border.all(color: kBorderColorTextField),
                                                            image: DecorationImage(image: NetworkImage(product.productPicture), fit: BoxFit.cover),
                                                          ),
                                                        ),
                                                      ),
                                                      DataCell(Text(product.productName)),
                                                      DataCell(Text(product.productCategory)),
                                                      DataCell(Text("$globalCurrency ${myFormat.format(double.tryParse(product.productSalePrice) ?? 0)}")),
                                                      DataCell(Text(myFormat.format(double.tryParse(product.productStock) ?? 0))),
                                                      DataCell(Text(DateFormat.yMMMd().format(expiryDate))),
                                                      DataCell(
                                                        Text(
                                                          isExpired ? 'Expired' : 'Expiring Soon',
                                                          style: theme.textTheme.bodyMedium?.copyWith(color: isExpired ? Colors.red : Colors.orange),
                                                        ),
                                                      ),
                                                      DataCell(
                                                        SizedBox(
                                                          height: 25,
                                                          width: 25,
                                                          child: StatefulBuilder(
                                                            builder: (BuildContext context, setState) {
                                                              return PopupMenuButton(
                                                                itemBuilder: (BuildContext bc) => [
                                                                  PopupMenuItem(
                                                                    onTap: () => context.push(
                                                                      '/product/edit-product',
                                                                      extra: {
                                                                        'productModel': product,
                                                                        'allProductsNameList': allProductsNameList,
                                                                        'groupTaxModel': groupTax.value ?? [],
                                                                      },
                                                                    ),
                                                                    child: Row(
                                                                      children: [
                                                                        Icon(IconlyLight.edit, size: 22.0, color: kGreyTextColor),
                                                                        const SizedBox(width: 4.0),
                                                                        Text('Edit', style: theme.textTheme.bodyLarge),
                                                                      ],
                                                                    ),
                                                                  ),
                                                                  PopupMenuItem(
                                                                    onTap: () async {
                                                                      await productStockEditPopUp(product: product, popUp: context, pref: ref);
                                                                    },
                                                                    child: Row(
                                                                      children: [
                                                                        const Icon(Icons.add, size: 22.0, color: kTitleColor),
                                                                        const SizedBox(width: 4.0),
                                                                        Text('Increase Stock', style: theme.textTheme.bodyLarge),
                                                                      ],
                                                                    ),
                                                                  ),
                                                                  PopupMenuItem(
                                                                    onTap: () {
                                                                      showDialog(
                                                                        context: context,
                                                                        builder: (BuildContext dialogContext) {
                                                                          return AlertDialog(
                                                                            title: Text('Delete Product'),
                                                                            content: Text('Are you sure you want to delete this product?'),
                                                                            actions: [
                                                                              TextButton(
                                                                                onPressed: () => Navigator.pop(dialogContext),
                                                                                child: Text('Cancel'),
                                                                              ),
                                                                              TextButton(
                                                                                onPressed: () {
                                                                                  if (!isDemo) {
                                                                                    deleteProduct(
                                                                                      productCode: product.productCode,
                                                                                      updateProduct: ref,
                                                                                      context: bc,
                                                                                    );
                                                                                    Navigator.pop(dialogContext);
                                                                                  } else {
                                                                                    EasyLoading.showInfo(demoText);
                                                                                  }
                                                                                },
                                                                                child: Text('Delete'),
                                                                              ),
                                                                            ],
                                                                          );
                                                                        },
                                                                      );
                                                                    },
                                                                    child: Row(
                                                                      children: [Icon(Icons.delete, color: kGreyTextColor, size: 22.0), const SizedBox(width: 5), Text('Delete', style: theme.textTheme.bodyLarge)],
                                                                    ),
                                                                  ),
                                                                ],
                                                                child: const Icon(Icons.more_vert_sharp, size: 18),
                                                              );
                                                            },
                                                          ),
                                                        ),
                                                      ),
                                                    ],
                                                  );
                                                },
                                              ),
                                            ),
                                          ),
                                        ),
                                      );
                                    },
                                  ),
                                ),
                                // Pagination controls
                                Padding(
                                  padding: const EdgeInsets.all(10.0),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      Text(
                                        'Showing ${((_currentPage - 1) * itemsPerPage + 1).toString()} to '
                                        '${min(_currentPage * itemsPerPage, expiredProducts.length)} '
                                        'of ${expiredProducts.length} entries',
                                      ),
                                      const Spacer(),
                                      Row(
                                        children: [
                                          InkWell(
                                            onTap: _currentPage > 1 ? () => setState(() => _currentPage--) : null,
                                            child: Container(
                                              height: 32,
                                              width: 90,
                                              decoration: BoxDecoration(
                                                border: Border.all(color: kBorderColorTextField),
                                                borderRadius: const BorderRadius.only(
                                                  bottomLeft: Radius.circular(4.0),
                                                  topLeft: Radius.circular(4.0),
                                                ),
                                              ),
                                              child: const Center(child: Text('Previous')),
                                            ),
                                          ),
                                          Container(
                                            height: 32,
                                            width: 32,
                                            decoration: BoxDecoration(
                                              border: Border.all(color: kMainColor),
                                              color: kMainColor,
                                            ),
                                            child: Center(
                                              child: Text(
                                                '$_currentPage',
                                                style: const TextStyle(color: Colors.white),
                                              ),
                                            ),
                                          ),
                                          InkWell(
                                            onTap: _currentPage * itemsPerPage < expiredProducts.length ? () => setState(() => _currentPage++) : null,
                                            child: Container(
                                              height: 32,
                                              width: 90,
                                              decoration: BoxDecoration(
                                                border: Border.all(color: kBorderColorTextField),
                                                borderRadius: const BorderRadius.only(
                                                  bottomRight: Radius.circular(4.0),
                                                  topRight: Radius.circular(4.0),
                                                ),
                                              ),
                                              child: const Center(child: Text('Next')),
                                            ),
                                          ),
                                        ],
                                      )
                                    ],
                                  ),
                                ),
                              ],
                            )
                          : EmptyWidget(title: lang.S.of(context).noProductFound),
                    ],
                  ),
                ),
              ),
            );
          }, error: (e, stack) {
            return Center(child: Text(e.toString()));
          }, loading: () {
            return const Center(child: CircularProgressIndicator());
          });
        },
      ),
    );
  }
}
