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:hugeicons/hugeicons.dart';
import 'package:iconly/iconly.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:responsive_grid/responsive_grid.dart';
import 'package:salespro_admin/generated/l10n.dart' as lang;
import 'package:salespro_admin/model/brands_model.dart';

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

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

  @override
  State<ProductBrand> createState() => _ProductBrandState();
}

class _ProductBrandState extends State<ProductBrand> {
  ScrollController mainScroll = ScrollController();
  String searchItem = '';
  final _horizontalScroll = ScrollController();
  int _stockReportPerPage = 10; // Default number of items to display
  int _currentPage = 1;
  final brandNameController = TextEditingController();
  final editBrandNameController = TextEditingController();

  Future<void> addBrandPopup({
    required WidgetRef ref,
    required List<String> brandNameList,
    required BuildContext addProductsContext,
  }) async {
    GlobalKey<FormState> brandNameKey = GlobalKey<FormState>();

    bool brandValidateAndSave() {
      final form = brandNameKey.currentState;
      if (form!.validate()) {
        form.save();
        return true;
      }
      return false;
    }

    showDialog(
      barrierDismissible: false,
      context: addProductsContext,
      builder: (BuildContext context) {
        return StatefulBuilder(builder: (context, setState) {
          return Dialog(
            surfaceTintColor: kWhite,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10.0),
            ),
            child: SizedBox(
              width: 600,
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.all(4.0),
                          decoration: const BoxDecoration(shape: BoxShape.rectangle),
                          child: const Icon(
                            FeatherIcons.plus,
                            color: kTitleColor,
                          ),
                        ),
                        const SizedBox(width: 4.0),
                        Text(
                          lang.S.of(context).addBrand,
                          style: kTextStyle.copyWith(color: kTitleColor, fontSize: 18.0, fontWeight: FontWeight.bold),
                        ),
                        const Spacer(),
                        const Icon(
                          FeatherIcons.x,
                          color: kTitleColor,
                          size: 21.0,
                        ).onTap(() {
                          brandNameController.clear();
                          finish(context);
                        })
                      ],
                    ),
                    const SizedBox(height: 20.0),
                    Divider(
                      thickness: 1.0,
                      color: kGreyTextColor.withOpacity(0.2),
                    ),
                    const SizedBox(height: 10.0),
                    Row(
                      children: [
                        Text(
                          lang.S.of(context).brandName,
                          style: kTextStyle.copyWith(color: kTitleColor, fontSize: 18.0),
                        ),
                        const SizedBox(width: 50),
                        Form(
                          key: brandNameKey,
                          child: SizedBox(
                            width: 400,
                            child: TextFormField(
                              validator: (value) {
                                if (value.isEmptyOrNull) {
                                  return 'Brand name is required.';
                                } else if (brandNameList.contains(value.removeAllWhiteSpace().toLowerCase())) {
                                  return 'Brand name already exists.';
                                } else {
                                  return null;
                                }
                              },
                              controller: brandNameController,
                              showCursor: true,
                              cursorColor: kTitleColor,
                              decoration: kInputDecoration.copyWith(
                                errorBorder: const OutlineInputBorder(borderSide: BorderSide(color: Colors.red)),
                                labelText: lang.S.of(context).brandName,
                                hintText: lang.S.of(context).enterBrandName,
                                hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 10.0),
                    Divider(
                      thickness: 1.0,
                      color: kGreyTextColor.withOpacity(0.2),
                    ),
                    const SizedBox(height: 5.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Container(
                          padding: const EdgeInsets.all(10.0),
                          decoration: BoxDecoration(borderRadius: BorderRadius.circular(5.0), color: kRedTextColor),
                          child: Text(
                            lang.S.of(context).cancel,
                            style: kTextStyle.copyWith(color: kWhite),
                          ),
                        ).onTap(() {
                          brandNameController.clear();
                          finish(context);
                        }),
                        const SizedBox(width: 5.0),
                        Container(
                          padding: const EdgeInsets.all(10.0),
                          decoration: BoxDecoration(borderRadius: BorderRadius.circular(5.0), color: kGreenTextColor),
                          child: Text(
                            lang.S.of(context).submit,
                            style: kTextStyle.copyWith(color: kWhite),
                          ),
                        ).onTap(() async {
                          if (brandValidateAndSave()) {
                            try {
                              EasyLoading.show(status: 'Adding Brand');
                              final DatabaseReference brandInformationRef = FirebaseDatabase.instance.ref().child(await getUserID()).child('Brands');
                              BrandsModel brandModel = BrandsModel(brandNameController.text);
                              await brandInformationRef.push().set(brandModel.toJson());
                              ref.refresh(brandProvider);
                              brandNameController.clear();
                              EasyLoading.showSuccess("Successfully Added");
                              finish(context);
                            } catch (e) {
                              EasyLoading.showError('Error');
                            }
                          }
                        })
                      ],
                    )
                  ],
                ),
              ),
            ),
          );
        });
      },
    );
  }

  Future<void> editBrandPopup({
    required WidgetRef ref,
    required BrandsModel brand,
    required List<String> brandNameList,
    required BuildContext editProductsContext,
  }) async {
    editBrandNameController.text = brand.brandName;

    GlobalKey<FormState> editBrandNameKey = GlobalKey<FormState>();

    bool brandValidateAndSave() {
      final form = editBrandNameKey.currentState;
      if (form!.validate()) {
        form.save();
        return true;
      }
      return false;
    }

    showDialog(
      barrierDismissible: false,
      context: editProductsContext,
      builder: (BuildContext context) {
        return StatefulBuilder(builder: (context, setState) {
          return Dialog(
            surfaceTintColor: kWhite,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10.0),
            ),
            child: SizedBox(
              width: 600,
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.all(4.0),
                          decoration: const BoxDecoration(shape: BoxShape.rectangle),
                          child: const Icon(
                            FeatherIcons.edit,
                            color: kTitleColor,
                          ),
                        ),
                        const SizedBox(width: 4.0),
                        Text(
                          'Edit Brand',
                          style: kTextStyle.copyWith(color: kTitleColor, fontSize: 18.0, fontWeight: FontWeight.bold),
                        ),
                        const Spacer(),
                        const Icon(
                          FeatherIcons.x,
                          color: kTitleColor,
                          size: 21.0,
                        ).onTap(() {
                          editBrandNameController.clear();
                          finish(context);
                        })
                      ],
                    ),
                    const SizedBox(height: 20.0),
                    Divider(
                      thickness: 1.0,
                      color: kGreyTextColor.withOpacity(0.2),
                    ),
                    const SizedBox(height: 10.0),
                    Row(
                      children: [
                        Text(
                          lang.S.of(context).brandName,
                          style: kTextStyle.copyWith(color: kTitleColor, fontSize: 18.0),
                        ),
                        const SizedBox(width: 50),
                        Form(
                          key: editBrandNameKey,
                          child: SizedBox(
                            width: 400,
                            child: TextFormField(
                              validator: (value) {
                                if (value.isEmptyOrNull) {
                                  return 'Brand name is required.';
                                } else if (value.removeAllWhiteSpace().toLowerCase() != brand.brandName.removeAllWhiteSpace().toLowerCase() && brandNameList.contains(value.removeAllWhiteSpace().toLowerCase())) {
                                  return 'Brand name already exists.';
                                } else {
                                  return null;
                                }
                              },
                              controller: editBrandNameController,
                              showCursor: true,
                              cursorColor: kTitleColor,
                              decoration: kInputDecoration.copyWith(
                                errorBorder: const OutlineInputBorder(borderSide: BorderSide(color: Colors.red)),
                                labelText: lang.S.of(context).brandName,
                                hintText: lang.S.of(context).enterBrandName,
                                hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 10.0),
                    Divider(
                      thickness: 1.0,
                      color: kGreyTextColor.withOpacity(0.2),
                    ),
                    const SizedBox(height: 5.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Container(
                          padding: const EdgeInsets.all(10.0),
                          decoration: BoxDecoration(borderRadius: BorderRadius.circular(5.0), color: kRedTextColor),
                          child: Text(
                            lang.S.of(context).cancel,
                            style: kTextStyle.copyWith(color: kWhite),
                          ),
                        ).onTap(() {
                          editBrandNameController.clear();
                          finish(context);
                        }),
                        const SizedBox(width: 5.0),
                        Container(
                          padding: const EdgeInsets.all(10.0),
                          decoration: BoxDecoration(borderRadius: BorderRadius.circular(5.0), color: kGreenTextColor),
                          child: Text(
                            lang.S.of(context).submit,
                            style: kTextStyle.copyWith(color: kWhite),
                          ),
                        ).onTap(() async {
                          if (brandValidateAndSave()) {
                            try {
                              EasyLoading.show(status: 'Updating Brand');
                              // Fetch the brand from Firebase to get the key
                              DatabaseEvent event = await FirebaseDatabase.instance.ref().child(await getUserID()).child('Brands').orderByChild('brandName').equalTo(brand.brandName).once();

                              if (event.snapshot.value != null) {
                                Map<dynamic, dynamic> values = event.snapshot.value as Map<dynamic, dynamic>;
                                String brandKey = values.keys.first;

                                // Update the brand in Firebase
                                await FirebaseDatabase.instance.ref().child(await getUserID()).child('Brands').child(brandKey).update({'brandName': editBrandNameController.text});

                                ref.refresh(brandProvider);
                                editBrandNameController.clear();
                                EasyLoading.showSuccess("Successfully Updated");
                                finish(context);
                              }
                            } catch (e) {
                              EasyLoading.showError('Error');
                            }
                          }
                        })
                      ],
                    )
                  ],
                ),
              ),
            ),
          );
        });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final screenWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      backgroundColor: kDarkWhite,
      body: SingleChildScrollView(
        child: Consumer(
          builder: (context, ref, __) {
            final brandList = ref.watch(brandProvider);
            return brandList.when(data: (brand) {
              // Filter only low stock products
              List<String> editBrandList = [];
              List<String> brandName = [];
              for (var element in brand) {
                brandName.add(element.brandName);
                editBrandList.add(element.brandName.toLowerCase().removeAllWhiteSpace());
              }

              List<BrandsModel> filteredProducts = [];
              for (var element in brand) {
                if (element.brandName.removeAllWhiteSpace().toLowerCase().contains(searchItem.removeAllWhiteSpace().toLowerCase())) {
                  filteredProducts.add(element);
                }
              }

              final pages = (filteredProducts.length / _stockReportPerPage).ceil();
              final startIndex = (_currentPage - 1) * _stockReportPerPage;
              final endIndex = _stockReportPerPage == -1 ? filteredProducts.length : startIndex + _stockReportPerPage;
              final paginatedList = filteredProducts.sublist(
                startIndex,
                endIndex > filteredProducts.length ? filteredProducts.length : endIndex,
              );

              return SingleChildScrollView(
                padding: EdgeInsets.all(10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      width: double.infinity,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10.0),
                        color: kWhite,
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(left: 12, right: 12, top: 12),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Flexible(
                                  child: Text(
                                    'Brand List',
                                    style: theme.textTheme.titleLarge?.copyWith(
                                      fontWeight: FontWeight.w600,
                                    ),
                                    maxLines: 2,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                ElevatedButton.icon(
                                  onPressed: () async {
                                    if (await checkUserRolePermission(type: "brand-create")) {
                                      addBrandPopup(
                                        ref: ref,
                                        brandNameList: editBrandList,
                                        addProductsContext: context,
                                      );
                                    }
                                  },
                                  icon: const Icon(FeatherIcons.plus, color: kWhite, size: 18.0),
                                  label: Text(
                                    lang.S.of(context).addBrand,
                                    style: kTextStyle.copyWith(color: kWhite),
                                  ),
                                )
                              ],
                            ),
                          ),
                          const SizedBox(height: 10),
                          const Divider(
                            thickness: 1.0,
                            color: kNeutral300,
                            height: 1,
                          ),
                          const SizedBox(height: 10),
                          ResponsiveGridRow(rowSegments: 100, children: [
                            ResponsiveGridCol(
                              xs: screenWidth < 360
                                  ? 45
                                  : screenWidth > 430
                                      ? 35
                                      : 40,
                              md: screenWidth < 768
                                  ? 24
                                  : screenWidth < 950
                                      ? 20
                                      : 15,
                              lg: screenWidth < 1700 ? 14 : 10,
                              child: Padding(
                                padding: const EdgeInsets.all(10.0),
                                child: Container(
                                  alignment: Alignment.center,
                                  height: 48,
                                  padding: const EdgeInsets.all(6),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(8.0),
                                    border: Border.all(color: kThemeOutlineColor),
                                  ),
                                  child: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Flexible(
                                          child: Text(
                                        'Show-',
                                        style: theme.textTheme.bodyLarge,
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                      )),
                                      DropdownButton<int>(
                                        isDense: true,
                                        padding: EdgeInsets.zero,
                                        underline: const SizedBox(),
                                        value: _stockReportPerPage,
                                        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(() {
                                            if (newValue == -1) {
                                              _stockReportPerPage = -1;
                                            } else {
                                              _stockReportPerPage = newValue ?? 10;
                                            }
                                            _currentPage = 1;
                                          });
                                        },
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                            ResponsiveGridCol(
                              xs: 100,
                              md: 60,
                              lg: 35,
                              child: Padding(
                                padding: const EdgeInsets.all(10.0),
                                child: TextFormField(
                                  showCursor: true,
                                  cursorColor: kTitleColor,
                                  onChanged: (value) {
                                    setState(() {
                                      searchItem = value;
                                    });
                                  },
                                  keyboardType: TextInputType.name,
                                  decoration: InputDecoration(
                                    contentPadding: const EdgeInsets.all(10.0),
                                    hintText: (lang.S.of(context).searchByName),
                                    border: InputBorder.none,
                                    suffixIcon: const Icon(
                                      FeatherIcons.search,
                                      color: kTitleColor,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ]),
                          filteredProducts.isNotEmpty
                              ? Column(
                                  children: [
                                    LayoutBuilder(
                                      builder: (BuildContext context, BoxConstraints constraints) {
                                        return Scrollbar(
                                          controller: _horizontalScroll,
                                          thumbVisibility: true,
                                          radius: const Radius.circular(8),
                                          thickness: 8,
                                          child: SingleChildScrollView(
                                            scrollDirection: Axis.horizontal,
                                            controller: _horizontalScroll,
                                            child: Theme(
                                              data: ThemeData(
                                                dividerColor: kNeutral300,
                                                textTheme: theme.textTheme,
                                              ),
                                              child: ConstrainedBox(
                                                constraints: BoxConstraints(
                                                  minWidth: constraints.maxWidth,
                                                  minHeight: MediaQuery.of(context).size.height - 345,
                                                ),
                                                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,
                                                  columns: [
                                                    DataColumn(
                                                      label: Text(
                                                        lang.S.of(context).SL,
                                                      ),
                                                    ),
                                                    DataColumn(
                                                      label: Text(
                                                        lang.S.of(context).brandName,
                                                      ),
                                                    ),
                                                    const DataColumn(label: Icon(FeatherIcons.settings)),
                                                  ],
                                                  rows: List.generate(
                                                    paginatedList.length,
                                                    (index) {
                                                      final product = paginatedList[index];

                                                      return DataRow(
                                                        cells: [
                                                          DataCell(Text(
                                                            "${startIndex + index + 1}",
                                                          )),
                                                          DataCell(
                                                            Text(
                                                              product.brandName,
                                                            ),
                                                          ),
                                                          DataCell(
                                                            Theme(
                                                              data: ThemeData(highlightColor: dropdownItemColor, focusColor: dropdownItemColor, hoverColor: dropdownItemColor),
                                                              child: SizedBox(
                                                                width: 20,
                                                                child: PopupMenuButton(
                                                                  surfaceTintColor: Colors.white,
                                                                  padding: EdgeInsets.zero,
                                                                  itemBuilder: (BuildContext bc) => [
                                                                    ///____________Edit____________________________________________________
                                                                    PopupMenuItem(
                                                                      onTap: () async {
                                                                        if (await checkUserRolePermission(type: "brand-update")) {
                                                                          // Wait for the popup to close
                                                                          await Future.delayed(Duration.zero);
                                                                          editBrandPopup(
                                                                            ref: ref,
                                                                            brand: product,
                                                                            brandNameList: editBrandList,
                                                                            editProductsContext: context,
                                                                          );
                                                                        }
                                                                      },
                                                                      child: Row(
                                                                        children: [
                                                                          const Icon(IconlyLight.edit, size: 20.0, color: kNeutral500),
                                                                          const SizedBox(width: 4.0),
                                                                          Text(
                                                                            lang.S.of(context).edit,
                                                                            style: theme.textTheme.bodyLarge?.copyWith(
                                                                              color: kNeutral500,
                                                                            ),
                                                                          ),
                                                                        ],
                                                                      ),
                                                                    ),

                                                                    ///____________delete___________________________________________________
                                                                    PopupMenuItem(
                                                                      onTap: () async {
                                                                        if (await checkUserRolePermission(type: "brand-delete")) {
                                                                          // Wait for the popup to close
                                                                          await Future.delayed(Duration.zero);

                                                                          showDialog(
                                                                              barrierDismissible: false,
                                                                              context: context,
                                                                              builder: (BuildContext dialogContext) {
                                                                                return Center(
                                                                                  child: Container(
                                                                                    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(
                                                                                            'Are you sure you want to delete this brand?',
                                                                                            style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w600),
                                                                                          ),
                                                                                          const SizedBox(height: 20),
                                                                                          Row(
                                                                                            mainAxisAlignment: MainAxisAlignment.center,
                                                                                            mainAxisSize: MainAxisSize.min,
                                                                                            children: [
                                                                                              ElevatedButton(
                                                                                                style: ElevatedButton.styleFrom(
                                                                                                  backgroundColor: Colors.red,
                                                                                                ),
                                                                                                onPressed: () {
                                                                                                  GoRouter.of(context).pop();
                                                                                                },
                                                                                                child: Text(
                                                                                                  lang.S.of(context).cancel,
                                                                                                ),
                                                                                              ),
                                                                                              SizedBox(width: screenWidth < 570 ? 10 : 30),
                                                                                              ElevatedButton(
                                                                                                onPressed: () async {
                                                                                                  try {
                                                                                                    EasyLoading.show(status: 'Deleting Brand');
                                                                                                    // Fetch the brand from Firebase to get the key
                                                                                                    DatabaseEvent event = await FirebaseDatabase.instance.ref().child(await getUserID()).child('Brands').orderByChild('brandName').equalTo(product.brandName).once();

                                                                                                    if (event.snapshot.value != null) {
                                                                                                      Map<dynamic, dynamic> values = event.snapshot.value as Map<dynamic, dynamic>;
                                                                                                      String brandKey = values.keys.first;

                                                                                                      // Delete the brand from Firebase
                                                                                                      await FirebaseDatabase.instance.ref().child(await getUserID()).child('Brands').child(brandKey).remove();

                                                                                                      ref.refresh(brandProvider);
                                                                                                      EasyLoading.showSuccess('Deleted Successfully');
                                                                                                      GoRouter.of(context).pop();
                                                                                                    }
                                                                                                  } catch (e) {
                                                                                                    EasyLoading.showError('Error deleting brand');
                                                                                                  }
                                                                                                },
                                                                                                child: Text(
                                                                                                  lang.S.of(context).delete,
                                                                                                ),
                                                                                              ),
                                                                                            ],
                                                                                          )
                                                                                        ],
                                                                                      ),
                                                                                    ),
                                                                                  ),
                                                                                );
                                                                              });
                                                                        }
                                                                      },
                                                                      child: Row(
                                                                        children: [
                                                                          const HugeIcon(
                                                                            icon: HugeIcons.strokeRoundedDelete02,
                                                                            color: kNeutral500,
                                                                            size: 20.0,
                                                                          ),
                                                                          const SizedBox(width: 4.0),
                                                                          Text(
                                                                            lang.S.of(context).delete,
                                                                            style: theme.textTheme.bodyLarge?.copyWith(color: kNeutral500),
                                                                          ),
                                                                        ],
                                                                      ),
                                                                    ),
                                                                  ],
                                                                  onSelected: (value) {
                                                                    // Navigator.pushNamed(context, '$value');
                                                                    context.go('/$value');
                                                                  },
                                                                  child: Center(
                                                                    child: Container(
                                                                        height: 18,
                                                                        width: 18,
                                                                        alignment: Alignment.centerRight,
                                                                        child: const Icon(
                                                                          Icons.more_vert_sharp,
                                                                          size: 18,
                                                                        )),
                                                                  ),
                                                                ),
                                                              ),
                                                            ),
                                                          ),
                                                        ],
                                                      );
                                                    },
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ),
                                        );
                                      },
                                    ),
                                    Padding(
                                      padding: const EdgeInsets.all(10.0),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Flexible(
                                            child: Text(
                                              '${lang.S.of(context).showing} ${((_currentPage - 1) * _stockReportPerPage + 1).toString()} to ${((_currentPage - 1) * _stockReportPerPage + _stockReportPerPage).clamp(0, filteredProducts.length)} of ${filteredProducts.length} entries',
                                              maxLines: 2,
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                          Row(
                                            children: [
                                              InkWell(
                                                overlayColor: WidgetStateProperty.all<Color>(Colors.grey),
                                                hoverColor: Colors.grey,
                                                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: Center(
                                                    child: Text(lang.S.of(context).previous),
                                                  ),
                                                ),
                                              ),
                                              Container(
                                                height: 32,
                                                width: 32,
                                                decoration: BoxDecoration(
                                                  border: Border.all(color: kBorderColorTextField),
                                                  color: kMainColor,
                                                ),
                                                child: Center(
                                                  child: Text(
                                                    '$_currentPage',
                                                    style: const TextStyle(color: Colors.white),
                                                  ),
                                                ),
                                              ),
                                              Container(
                                                height: 32,
                                                width: 32,
                                                decoration: BoxDecoration(
                                                  border: Border.all(color: kBorderColorTextField),
                                                  color: Colors.transparent,
                                                ),
                                                child: Center(
                                                  child: Text(
                                                    '$pages',
                                                  ),
                                                ),
                                              ),
                                              InkWell(
                                                hoverColor: Colors.blue.withValues(alpha: 0.1),
                                                overlayColor: WidgetStateProperty.all<Color>(Colors.blue),
                                                onTap: _currentPage * _stockReportPerPage < filteredProducts.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(),
              );
            });
          },
        ),
      ),
    );
  }
}
