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/unit_model.dart';

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

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

  @override
  State<ProductUnit> createState() => _ProductUnitState();
}

class _ProductUnitState extends State<ProductUnit> {
  ScrollController mainScroll = ScrollController();
  String searchItem = '';
  final _horizontalScroll = ScrollController();
  int _stockReportPerPage = 10; // Default number of items to display
  int _currentPage = 1;
  final unitNameController = TextEditingController();
  final editUnitNameController = TextEditingController();
  final descriptionController = TextEditingController();

  void addUnitPopUp({
    required WidgetRef ref,
    required List<String> unitNameList,
    required BuildContext addProductsContext,
  }) {
    GlobalKey<FormState> unitNameKey = GlobalKey<FormState>();

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

    showDialog(
        barrierDismissible: true,
        context: addProductsContext,
        builder: (BuildContext context) {
          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,
                  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).addUnit,
                          style: kTextStyle.copyWith(color: kTitleColor, fontSize: 18.0, fontWeight: FontWeight.bold),
                        ),
                        const Spacer(),
                        const Icon(
                          FeatherIcons.x,
                          color: kTitleColor,
                          size: 21.0,
                        ).onTap(() {
                          unitNameController.clear();
                          descriptionController.clear();
                          finish(context);
                        })
                      ],
                    ),
                    const SizedBox(height: 20.0),
                    Divider(
                      thickness: 1.0,
                      color: kGreyTextColor.withValues(alpha: 0.2),
                    ),
                    const SizedBox(height: 10.0),
                    Row(
                      children: [
                        Text(
                          lang.S.of(context).unitName,
                          style: kTextStyle.copyWith(color: kTitleColor, fontSize: 18.0),
                        ),
                        const SizedBox(width: 50),
                        Form(
                          key: unitNameKey,
                          child: SizedBox(
                            width: 400,
                            child: TextFormField(
                              validator: (value) {
                                if (value.isEmptyOrNull) {
                                  return 'Unit name is required.';
                                } else if (unitNameList.contains(value.removeAllWhiteSpace().toLowerCase())) {
                                  return 'Unit name already exists.';
                                } else {
                                  return null;
                                }
                              },
                              controller: unitNameController,
                              showCursor: true,
                              cursorColor: kTitleColor,
                              decoration: kInputDecoration.copyWith(
                                errorBorder: const OutlineInputBorder(borderSide: BorderSide(color: Colors.red)),
                                labelText: lang.S.of(context).unitName,
                                hintText: lang.S.of(context).enterUnitName,
                                hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 5.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(() {
                          unitNameController.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 (unitValidateAndSave()) {
                            try {
                              EasyLoading.show(status: 'Adding Unit');
                              final DatabaseReference unitInformationRef = FirebaseDatabase.instance.ref().child(await getUserID()).child('Units');
                              UnitModel unitModel = UnitModel(unitNameController.text);
                              await unitInformationRef.push().set(unitModel.toJson());
                              ref.refresh(unitProvider);
                              setState(() {
                                unitTime = 0;
                                extraAddedUnits.clear();
                              });
                              unitNameController.clear();
                              EasyLoading.showSuccess("Successfully Added");
                              finish(context);
                            } catch (e) {
                              EasyLoading.showError('Error adding unit');
                            }
                          }
                        })
                      ],
                    )
                  ],
                ),
              ),
            ),
          );
        });
  }

  void editUnitPopUp({
    required WidgetRef ref,
    required UnitModel unit,
    required List<String> unitNameList,
    required BuildContext editProductsContext,
  }) {
    editUnitNameController.text = unit.unitName;
    GlobalKey<FormState> editUnitNameKey = GlobalKey<FormState>();

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

    showDialog(
        barrierDismissible: true,
        context: editProductsContext,
        builder: (BuildContext context) {
          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,
                  children: [
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.all(4.0),
                          decoration: const BoxDecoration(shape: BoxShape.rectangle),
                          child: const Icon(
                            IconlyLight.edit,
                            color: kTitleColor,
                          ),
                        ),
                        const SizedBox(width: 4.0),
                        Text(
                          'Edit Unit',
                          style: kTextStyle.copyWith(color: kTitleColor, fontSize: 18.0, fontWeight: FontWeight.bold),
                        ),
                        const Spacer(),
                        const Icon(
                          FeatherIcons.x,
                          color: kTitleColor,
                          size: 21.0,
                        ).onTap(() {
                          editUnitNameController.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(
                          'Unit Name',
                          style: kTextStyle.copyWith(color: kTitleColor, fontSize: 18.0),
                        ),
                        const SizedBox(width: 50),
                        Form(
                          key: editUnitNameKey,
                          child: SizedBox(
                            width: 400,
                            child: TextFormField(
                              validator: (value) {
                                if (value.isEmptyOrNull) {
                                  return 'Unit name is required.';
                                } else if (unitNameList.contains(value.removeAllWhiteSpace().toLowerCase()) && value.removeAllWhiteSpace().toLowerCase() != unit.unitName.removeAllWhiteSpace().toLowerCase()) {
                                  return 'Unit name already exists.';
                                } else {
                                  return null;
                                }
                              },
                              controller: editUnitNameController,
                              showCursor: true,
                              cursorColor: kTitleColor,
                              decoration: kInputDecoration.copyWith(
                                errorBorder: const OutlineInputBorder(borderSide: BorderSide(color: Colors.red)),
                                labelText: 'Unit Name',
                                hintText: 'Enter unit name',
                                hintStyle: kTextStyle.copyWith(color: kGreyTextColor),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 5.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(() {
                          editUnitNameController.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(
                            'Update',
                            style: kTextStyle.copyWith(color: kWhite),
                          ),
                        ).onTap(() async {
                          if (unitValidateAndSave()) {
                            try {
                              EasyLoading.show(status: 'Updating Unit');
                              // Fetch the unit from Firebase to get the key
                              DatabaseEvent event = await FirebaseDatabase.instance.ref().child(await getUserID()).child('Units').orderByChild('unitName').equalTo(unit.unitName).once();

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

                                // Update the unit in Firebase
                                await FirebaseDatabase.instance.ref().child(await getUserID()).child('Units').child(unitKey).update({
                                  'unitName': editUnitNameController.text,
                                });

                                ref.refresh(unitProvider);
                                EasyLoading.showSuccess("Successfully Updated");
                                editUnitNameController.clear();
                                finish(context);
                              }
                            } catch (e) {
                              EasyLoading.showError('Error updating unit');
                            }
                          }
                        })
                      ],
                    )
                  ],
                ),
              ),
            ),
          );
        });
  }

  List<String> extraAddedUnits = [];
  List<String> allUnitList = [];
  int unitTime = 0;

  @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 unitList = ref.watch(unitProvider);
            return unitList.when(data: (units) {
              List<String> editUnitNameList = [];

              if (unitTime == 0) {
                extraAddedUnits = units.map((e) => e.unitName).toList();
                allUnitList = List.from(extraAddedUnits);
                unitTime++;
              }

              for (var element in allUnitList) {
                editUnitNameList.add(element.removeAllWhiteSpace().toLowerCase());
              }

              List<UnitModel> filteredProducts = units.where((element) {
                return element.unitName.removeAllWhiteSpace().toLowerCase().contains(searchItem.removeAllWhiteSpace().toLowerCase());
              }).toList();

              final pages = (_stockReportPerPage == -1 ? 1 : (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: const 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(
                                    'Unit List',
                                    style: theme.textTheme.titleLarge?.copyWith(
                                      fontWeight: FontWeight.w600,
                                    ),
                                    maxLines: 2,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                ElevatedButton.icon(
                                  onPressed: () async {
                                    if (await checkUserRolePermission(type: "unit-create")) {
                                      addUnitPopUp(
                                        ref: ref,
                                        unitNameList: editUnitNameList,
                                        addProductsContext: context,
                                      );
                                    }
                                  },
                                  icon: const Icon(FeatherIcons.plus, color: kWhite, size: 18.0),
                                  label: Text(
                                    lang.S.of(context).addUnit,
                                    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).unitName,
                                                      ),
                                                    ),
                                                    const DataColumn(label: Icon(FeatherIcons.settings)),
                                                  ],
                                                  rows: List.generate(
                                                    paginatedList.length,
                                                    (index) {
                                                      final unit = paginatedList[index];

                                                      return DataRow(
                                                        cells: [
                                                          DataCell(Text(
                                                            "${startIndex + index + 1}",
                                                          )),
                                                          DataCell(
                                                            Text(
                                                              unit.unitName,
                                                            ),
                                                          ),
                                                          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 {
                                                                        // Wait for the popup to close
                                                                        if (await checkUserRolePermission(type: "unit-update")) {
                                                                          await Future.delayed(Duration.zero);
                                                                          editUnitPopUp(
                                                                            ref: ref,
                                                                            unit: unit,
                                                                            unitNameList: editUnitNameList,
                                                                            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 {
                                                                        // Wait for the popup to close
                                                                        if (await checkUserRolePermission(type: "unit-delete")) {
                                                                          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 unit?',
                                                                                            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 Unit');
                                                                                                    // Fetch the unit from Firebase to get the key
                                                                                                    DatabaseEvent event = await FirebaseDatabase.instance.ref().child(await getUserID()).child('Units').orderByChild('unitName').equalTo(unit.unitName).once();

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

                                                                                                      // Delete the unit from Firebase
                                                                                                      await FirebaseDatabase.instance.ref().child(await getUserID()).child('Units').child(unitKey).remove();

                                                                                                      ref.refresh(unitProvider);
                                                                                                      EasyLoading.showSuccess('Deleted Successfully');
                                                                                                      GoRouter.of(context).pop();
                                                                                                    }
                                                                                                  } catch (e) {
                                                                                                    EasyLoading.showError('Error deleting unit');
                                                                                                  }
                                                                                                },
                                                                                                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 + paginatedList.length).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 < pages ? () => 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(),
              );
            });
          },
        ),
      ),
    );
  }
}
