// import 'dart:html';

// ignore_for_file: sized_box_for_whitespace, avoid_unnecessary_containers

import 'package:byod/bloc/filter_menu.dart';
import 'package:byod/bloc/order_bloc.dart';
import 'package:byod/bloc/search_menu.dart';
import 'package:byod/helper/helper.dart';
import 'package:byod/helper/widget/style.dart';
import 'package:byod/models/category_list.dart';
import 'package:byod/models/filter_menu.dart';
import 'package:byod/models/orders.dart';
import 'package:byod/ui/checkout/checkout.dart';
import 'package:byod/ui/home/menu.dart';
import 'package:byod/ui/screen_responsive.dart';
import 'package:byod/ui/viewbill/view_bill.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../../bloc/branch_exist.dart';
import '../../helper/widget/button_dialog.dart';
import '../../main.dart';
import '../../models/fav_group.dart';
import '../checkout/fuction.dart';
import 'shimmer_menu.dart';

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  String tableNumber = prefs.getString("table_number") ?? "";
  String userName = prefs.getString("userName") ?? "";
  final searchController = TextEditingController();
  final _scrollController = ScrollController();
  bool isSearch = true;
  bool isScroll = false;
  late int countCategoryToDisplay = 1; // count as array
  late int countMenuToDisplay = maxItemMenu; // count as array
  late List<FilterMenu> allMenu = [];
  final nameController = TextEditingController();

  @override
  void initState() {
    _scrollController.addListener(() {
      if (_scrollController.position.pixels >=
          (_scrollController.position.maxScrollExtent - 100)) {
        if (allMenu.length >= countMenuToDisplay) {
          _getMoreData(countMenuToDisplay, allMenu);
        }
      }
    });

    super.initState();
  }

  _getMoreData(int menuToDisplay, List<FilterMenu> allMenu) {
    setState(() {
      if ((allMenu.length - countMenuToDisplay) > maxItemMenu) {
        countMenuToDisplay += maxItemMenu;
      } else {
        countMenuToDisplay = allMenu.length;
      }
    });
  }

  @override
  void dispose() {
    _scrollController.removeListener(() {});
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    int tableMode = prefs.getInt('table_mode') ?? defaultTable;
    // context.read<FeedBackOptionBloc>().getOptionFeedback();
    double widthScreen = responsiveWidthScreen(context);
    double maxWidthScreen = getMaxWidthScreen(context, useResponsive);
    return BlocBuilder<BranchExist, String>(
      builder: (contextBracnhExist, restoran) {
        // (restoran != '')
        //     ? context.read<CategoryMenu>().catAndMenu(widget.param)
        //     : null;
        void onTapOkPop() {
          Navigator.pop(context, true);
        }

        void onTapOkNoPop() {
          Navigator.pop(context, false);
        }

        return WillPopScope(
          onWillPop: () async {
            if (!isSearch) {
              setState(() {
                isSearch = true;
              });
              return false;
            } else {
              final shouldPop = await buttonDialogGlobal(
                context,
                'Konfirmasi',
                'Apakah anda ingin keluar dari website ?',
                'Ya',
                'Batal',
                onTapOkPop,
                onTapOkNoPop,
                okButtonColor: buttonColor,
                cancelButtonColor: cancelColorButton,
              );

              return shouldPop ?? false;
            }
          },
          child: SafeArea(
            child: Scaffold(
              backgroundColor: backgroundColor,
              body: (restoran == responseByodBranchExist)
                  ? BlocBuilder<FilterMenuBloc, List<FilterMenu>>(
                      builder: (contextBlocListCat, categoryDefault) {
                        if (categoryDefault.isNotEmpty &&
                            categoryDefault[0].id == "0") {
                          return errorResponseByod(
                              'Gagal mendapatkan menu, silahkan refresh halaman / scan ulang barcode');
                        } else if (categoryDefault.isNotEmpty) {
                          List<FilterMenu> categoryNonFav = [];
                          List<FilterMenu> categoryFav = [];
                          for (var menu in categoryDefault) {
                            if (!menu.isFavMenu) {
                              categoryNonFav.add(menu);
                            } else {
                              categoryFav.add(menu);
                            }
                          }
                          allMenu = categoryNonFav;
                          List<CategoryList> categoryList = [];
                          List<FavoriteGroup> favList = [];
                          var nn = {
                            "name": "All"
                          }; // all dulu, biar ada bisa klik all
                          categoryList.add(CategoryList.createCategoryList(nn));
                          for (var nameCat in categoryNonFav) {
                            if (nameCat.type == typeCategory) {
                              var n = {"name": nameCat.categoryName};
                              categoryList
                                  .add(CategoryList.createCategoryList(n));
                            }
                          }
                          for (var nameFav in categoryFav) {
                            if (nameFav.type == typeCategory) {
                              var nfav = {
                                "name": nameFav.categoryName,
                                "id": nameFav.id
                              };
                              favList.add(FavoriteGroup.add(nfav));
                            }
                          }
                          // return coreHome(
                          //     categoryDefault, categoryList, widthScreen);
                          return ScreenResponsive(
                            widget: coreHome(
                              categoryNonFav,
                              categoryFav,
                              categoryList,
                              widthScreen,
                              maxWidthScreen,
                              context,
                              tableMode,
                              favList,
                            ),
                            widthScreen: MediaQuery.of(context).size.width,
                            isCoreLayout: true,
                          );
                        } else {
                          return ScreenResponsive(
                            widget: ShimmerMenu(
                                widthScreen: widthScreen,
                                maxWidthScreen: maxWidthScreen,
                                context: context),
                            widthScreen: MediaQuery.of(context).size.width,
                            isCoreLayout: true,
                          );
                        }
                      },
                    )
                  : (restoran == responseByodInActive)
                      ? errorResponseByod(
                          "Byod tidak aktif, untuk melakukan pesanan silakan memanggil waiter")
                      : (restoran == responseApiNoSuccess)
                          ? errorResponseByod(
                              "Scan QR Atau Kunjungi Alamat Outlet")
                          : (restoran == responseApiErrorServer)
                              ? errorResponseByod(
                                  "Something Went Wrong With Our Server")
                              : (restoran == responseApiWaiting)
                                  ? ScreenResponsive(
                                      widget: ShimmerMenu(
                                          widthScreen: widthScreen,
                                          maxWidthScreen: maxWidthScreen,
                                          context: context),
                                      widthScreen:
                                          MediaQuery.of(context).size.width,
                                      isCoreLayout: true,
                                    )
                                  : const SizedBox(),
            ),
          ),
        );
      },
    );
  }

  BlocBuilder<SearchMenu, List<dynamic>> coreHome(
    List<FilterMenu> categoryNonFav,
    List<FilterMenu> categoryFav,
    List<CategoryList> categoryList,
    double widthScreen,
    double maxWidthScreen,
    BuildContext context,
    int tableMode,
    List<FavoriteGroup> favList,
  ) {
    return BlocBuilder<SearchMenu, List<dynamic>>(
      builder: (contextListDynamic, selectedCategory) {
        List<FilterMenu> categoryMenu;
        if (selectedCategory[0].isNotEmpty && selectedCategory[2] == false) {
          allMenu = selectedCategory[0];
          categoryMenu = selectedCategory[0];
        } else {
          categoryMenu = categoryNonFav;
          allMenu = categoryNonFav;
        }
        return SingleChildScrollView(
          // controller: _scrollController,
          child: Container(
            // margin: EdgeInsets.all(
            //     MediaQuery.of(context).size.width * 0.04),
            width:
                (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
            padding: EdgeInsets.only(
              top: MediaQuery.of(context).size.height * 0.015,
              left: widthScreen * 0.04,
              right: widthScreen * 0.04,
            ),
            child: BlocBuilder<OrdersBloc, List<Orders>>(
              builder: (contextListOrders, listOrders) {
                // print("baaa");
                int totalItem = 0;
                int totalHarga = 0;
                if (listOrders.isNotEmpty) {
                  int fixTotalHarga = 0;
                  int totalHargaOrderDetail = 0;
                  int totalHargaBukanOrderDetail = 0;

                  int fixTotalItem = 0;
                  int totalItemOrderDetail = 0;
                  int totalItemBukanOrderDetail = 0;
                  for (var i = 0; i < listOrders.length; i++) {
                    // totalItem += listOrders[i].totalItem;
                    // check apakah ada order detail. kalau ada rekalkulasi total harga sesuai order detail
                    if (listOrders[i].orderDetail.isEmpty) {
                      totalHargaBukanOrderDetail +=
                          (listOrders[i].totalItem * listOrders[i].totalHarga);
                      totalItemBukanOrderDetail += listOrders[i].totalItem;
                    } else {
                      for (int kk = 0;
                          kk < listOrders[i].orderDetail.length;
                          kk++) {
                        totalHargaOrderDetail +=
                            listOrders[i].orderDetail[kk].totalHarga;
                        totalItemOrderDetail +=
                            listOrders[i].orderDetail[kk].totalItem;
                      }
                      fixTotalHarga = totalHargaOrderDetail;
                      fixTotalItem = totalItemOrderDetail;
                    }
                  }
                  totalHarga = fixTotalHarga + totalHargaBukanOrderDetail;
                  totalItem = fixTotalItem + totalItemBukanOrderDetail;
                }
                return Column(
                  children: [
                    Stack(
                      children: [
                        Column(
                          children: [
                            customAppbar(
                              context,
                              tableNumber,
                              userName,
                              categoryMenu,
                              categoryNonFav,
                              categoryFav,
                              categoryList,
                              selectedCategory,
                              widthScreen,
                              maxWidthScreen,
                              favList,
                            ),
                            Container(
                              height: (isSearch)
                                  ? (favList.isNotEmpty)
                                      ? MediaQuery.of(context).size.height *
                                          0.805
                                      : MediaQuery.of(context).size.height *
                                          0.865
                                  : MediaQuery.of(context).size.height * 0.915,
                              width: widthScreen,
                              // color: Colors.red,
                              child: BlocBuilder<SearchMenu, List<dynamic>>(
                                  builder: (contextListMenu, listMenuSearch) {
                                // print(listMenuSearch[0]);
                                return (isSearch == true)
                                    ? listViewCategory(
                                        categoryMenu, totalItem, widthScreen)
                                    : listViewCategory(
                                        (listMenuSearch[0].isNotEmpty)
                                            ? listMenuSearch[0]
                                            : [],
                                        totalItem,
                                        widthScreen,
                                      );
                              }),
                            ),
                          ],
                        ),
                        Positioned(
                            bottom: MediaQuery.of(context).size.height *
                                positionedBottom,
                            child: AnimatedSwitcher(
                                duration: Duration(milliseconds: animatedTime),
                                transitionBuilder: (child, animation) =>
                                    ScaleTransition(
                                        scale: animation, child: child),
                                child: (totalItem > 0)
                                    ? goTocheckOut(
                                        context,
                                        totalItem,
                                        totalHarga,
                                        widthScreen,
                                        tableMode,
                                        listOrders)
                                    : const SizedBox()))
                      ],
                    ),
                  ],
                );
              },
            ),
          ),
        );
      },
    );
  }

  Center errorResponseByod(String message) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          fontAwesome(
            context,
            timesCircleIcon,
            timesCircleIconSize,
            color: dangerColor,
            isBold: false,
          ),
          defaultText(
            context,
            message,
            textAlign: TextAlign.center,
            style: textStyleNormalFont(context),
          )
        ],
      ),
    );
  }

  ListView listViewCategory(
      List<FilterMenu> categoryMenu, int totalItem, double widthScreen) {
    return ListView.builder(
      controller: _scrollController,
      // physics:
      //     const NeverScrollableScrollPhysics(), // to disable GridView's scrolling
      shrinkWrap: false,
      itemCount: (categoryMenu.length) > countMenuToDisplay
          ? countMenuToDisplay
          : categoryMenu.length,
      itemBuilder: (context, i) {
        List<String> groupFiltering = [];
        if (categoryMenu[i].type == typeGroup) {
          groupFiltering.add(categoryMenu[i].groupId);
        }
        return Column(
          children: [
            (categoryMenu[i].type == typeCategory)
                ? Container(
                    height: MediaQuery.of(context).size.height * 0.06,
                    // color: Colors.green,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: textCategory(
                        context,
                        categoryMenu[i].categoryName,
                      ),
                    ),
                  )
                : const SizedBox(),
            (categoryMenu[i].type == typeCategory)
                ? SizedBox(
                    height: MediaQuery.of(context).size.height * 0.015,
                  )
                : const SizedBox(),
            (categoryMenu[i].type == typeGroup &&
                    categoryMenu[i].groupName != '')
                ? Column(
                    children: [
                      Divider(
                        thickness: widthScreen * 0.001,
                        color: Colors.grey,
                      ),
                      Container(
                        height: MediaQuery.of(context).size.height * 0.06,
                        // color: Colors.green,
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: textGroup(
                            context,
                            categoryMenu[i].groupName,
                          ),
                        ),
                      ),
                    ],
                  )
                : const SizedBox(),
            (categoryMenu[i].type == typeGroup &&
                    categoryMenu[i].groupName != '')
                ? SizedBox(
                    height: MediaQuery.of(context).size.height * 0.015,
                  )
                : const SizedBox(),
            (categoryMenu[i].type == typeMenu)
                ? MenuView(
                    isHaveItem: (totalItem == 0) ? false : true,
                    id: categoryMenu[i].id,
                    itemKe: i + 1,
                    itemCount: categoryMenu
                        .length, // harus sama dengan item count diatas, tujuan layouting
                    namaMenu: categoryMenu[i].name,
                    description: categoryMenu[i].description,
                    hargaCoret: amountParseToInt(categoryMenu[i].originalPrice),
                    hargaFix: amountParseToInt(categoryMenu[i].price),
                    imageUrl: categoryMenu[i].imageUrlThumbnail,
                    imageMedium: categoryMenu[i].imageUrlMedium,
                    isHaveVariant:
                        (categoryMenu[i].variantCat.isNotEmpty) ? true : false,
                    variantCat: categoryMenu[i].variantCat,
                    isSell: categoryMenu[i].isSell,
                    widthScreenParent: widthScreen,
                  )
                : const SizedBox(),
            (i != 0 &&
                    categoryMenu[i - 1].type == typeMenu &&
                    categoryMenu[i - 1].groupId != categoryMenu[i].groupId)
                ? SizedBox(
                    height: MediaQuery.of(context).size.height * 0.015,
                  )
                : const SizedBox(),
          ],
        );
      },
    );
  }

  GestureDetector goTocheckOut(BuildContext context, int totalItem,
      int totalHarga, widthScreen, int tableMode, List<Orders> listOrders) {
    String itemString = '';
    if (totalItem > 1) {
      itemString = 'Items';
    } else {
      itemString = 'Item';
    }
    return GestureDetector(
      onTap: () {
        String namaPelanggan = prefs.getString("userName") ?? '';
        if (tableMode == singleTable) {
          if (tableMode == singleTable && namaPelanggan != '') {
            checkOut(context, listOrders, namaPelanggan);
          } else {
            String namaPelanggan = prefs.getString("userName") ?? '';
            buttonDialog(
                context, namaPelanggan, listOrders, tableMode, widthScreen);
          }
        } else {
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => const CheckOut()));
        }
      },
      child: Container(
        height: MediaQuery.of(context).size.height * heigthButtonBottom,
        width: widthScreen * 0.92,
        // width: 50,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(roundedButton),
            color: buttonColor),
        child: Row(
          children: [
            Container(
              width: widthScreen * 0.35,
              height: double.infinity,
              padding: EdgeInsets.only(left: widthScreen * 0.05),
              // color: Colors.black,
              child: Align(
                  alignment: Alignment.centerLeft,
                  child: defaultText(
                    context,
                    "$totalItem $itemString",
                    style: textStyleNormalFont(
                      context,
                      color: textInButton,
                    ),
                  )),
            ),
            Container(
              width: widthScreen * 0.57,
              height: double.infinity,
              padding: EdgeInsets.only(right: widthScreen * 0.05),
              // color: Colors.red,
              child: Row(
                children: [
                  Container(
                    // color: Colors.red,
                    width: widthScreen * 0.4,
                    child: Align(
                      alignment: Alignment.centerRight,
                      child: defaultText(
                        context,
                        "Rp ${formatNumber().format(totalHarga)}",
                        style: textStyleNormalFont(
                          context,
                          color: textInButton,
                        ),
                      ),
                    ),
                  ),
                  Container(
                    // color: Colors.blue,
                    width: widthScreen * 0.12,
                    child: Align(
                      alignment: Alignment.center,
                      // child: Icon(Icons.shopping_bag_outlined,
                      //     size: MediaQuery.of(context).size.height * 0.03,
                      //     color: textInButton),
                      child: fontAwesome(
                        context,
                        shopingBag,
                        shopingBagSize,
                        color: textInButton,
                      ),
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  Container customAppbar(
    BuildContext context,
    String tableNumber,
    String userName,
    List<FilterMenu> category,
    List<FilterMenu> categoryDefault, // ini yang nonfav
    List<FilterMenu> categoryFav,
    List<CategoryList> categoryList,
    List<dynamic> selectedCategory,
    double widthScreen,
    double maxWidthScreen,
    List<FavoriteGroup> favList,
  ) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    String barName;
    if (userName != '') {
      barName = 'Meja $tableNumber - $userName';
    } else {
      barName = "Meja $tableNumber";
    }
    return Container(
      // height: MediaQuery.of(context).size.height * 0.12,
      height: (isSearch)
          ? (favList.isNotEmpty)
              ? MediaQuery.of(context).size.height * 0.18
              : MediaQuery.of(context).size.height * 0.12
          : MediaQuery.of(context).size.height * 0.07,
      // color: Colors.amber,
      width: (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
      child: Column(
        children: [
          Container(
            height: MediaQuery.of(context).size.height * 0.07,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                Container(
                  // color: Colors.red,
                  height: double.infinity,
                  width: widthScreen * 0.58,
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: (isSearch)
                        ? defaultText(
                            context,
                            barName,
                            overFlow: TextOverflow.ellipsis,
                            style: textStyleMenuList(context),
                          )
                        : TextField(
                            autofocus: true,
                            keyboardType: TextInputType.text,
                            controller: searchController,
                            onChanged: (sarchValue) {
                              context.read<SearchMenu>().searchMenu(
                                    categoryDefault,
                                    keyword: sarchValue.toString(),
                                    isSearch: true,
                                  );
                            },
                            // style: const TextStyle(color: Colors.black),
                            style: textStyleNormalFont(context),
                            decoration: InputDecoration(
                              border: InputBorder.none,
                              hintText: "Cari menu..",
                              hintStyle: TextStyle(
                                color: Colors.grey,
                                fontSize: MediaQuery.of(context).size.height *
                                    normalFont,
                              ),
                            ),
                          ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    if (isSearch == false) {
                      if (currentFocus.hasFocus) {
                        currentFocus.unfocus();
                      }
                      searchController.text = '';
                    }
                    Future.delayed(const Duration(milliseconds: 300), () async {
                      setState(() {
                        isSearch = !isSearch;
                      });
                    });
                    context.read<SearchMenu>().searchMenu(
                          categoryDefault,
                          keyword: '',
                          isSearch: true,
                          categorySelected: selectedCategory[1],
                        );
                  },
                  child: Container(
                    // color: Colors.blue,
                    height: double.infinity,
                    width: widthScreen * 0.1,
                    child: Align(
                      alignment: Alignment.center,
                      child: (isSearch)
                          ? fontAwesome(
                              context,
                              searchIcon,
                              searchIconSize,
                              color: Colors.grey,
                            )
                          : fontAwesome(
                              context,
                              timesIcon,
                              timesIconSize,
                              color: Colors.grey,
                            ),
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    Navigator.push(
                        context, MaterialPageRoute(builder: (_) => ViewBill()));
                  },
                  child: Container(
                    // color: Colors.blue,
                    height: double.infinity,
                    width: widthScreen * 0.17,
                    child: Column(
                      children: [
                        defaultText(
                          context,
                          "Pesanan",
                          style: textStyleNormalFont(
                            context,
                            font: categoryListFont,
                          ),
                        ),
                        Align(
                          alignment: Alignment.center,
                          child: fontAwesome(
                            context,
                            listPesanan,
                            listPesananSize,
                            color: buttonColor,
                          ),
                        ),
                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
          (isSearch)
              ? Column(
                  children: [
                    (favList.isNotEmpty)
                        ? favListBar(context, widthScreen, favList, categoryFav,
                            selectedCategory)
                        : const SizedBox(),
                    categoryListBar(context, widthScreen, categoryList,
                        categoryDefault, selectedCategory),
                  ],
                )
              : const SizedBox()
        ],
      ),
    );
  }

  Container categoryListBar(
      BuildContext context,
      double widthScreen,
      List<CategoryList> categoryList,
      List<FilterMenu> categoryDefault,
      List<dynamic> selectedCategory) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.04,
      // color: Colors.red,
      child: Row(
        children: [
          Container(
            // color: Colors.blue,
            width: widthScreen * 0.915,
            child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: categoryList.length,
                itemBuilder: (context, i) {
                  return GestureDetector(
                    onTap: () {
                      context.read<SearchMenu>().searchMenu(
                            categoryDefault,
                            categorySelected: categoryList[i].name,
                            isSearch: false,
                          );

                      _scrollController.animateTo(
                          _scrollController.position.minScrollExtent,
                          duration: const Duration(milliseconds: 100),
                          curve: Curves.fastOutSlowIn);
                      setState(() {
                        countCategoryToDisplay = 1;
                        countMenuToDisplay = maxItemMenu;
                      });
                    },
                    child: Container(
                      // width: MediaQuery.of(context).size.width * 0.25,
                      padding: EdgeInsets.all(
                          MediaQuery.of(context).size.height * 0.01),
                      margin: EdgeInsets.only(
                          left: (i == 0) ? 0 : widthScreen * 0.007,
                          right: (i == categoryList.length - 1)
                              ? 0
                              : widthScreen * 0.007),
                      height: double.infinity,
                      // color: Colors.blue,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(roundedButton),
                        color: (selectedCategory[1] == categoryList[i].name)
                            ? selectedColor
                            : buttonColor,
                      ),
                      child: Center(
                          child: defaultText(context, categoryList[i].name,
                              style: textStyleSelectedCategory(
                                context,
                              ))),
                    ),
                  );
                }),
          )
        ],
      ),
      // child: ListView.builder(itemBuilder: ),
    );
  }

  Container favListBar(
      BuildContext context,
      double widthScreen,
      List<FavoriteGroup> favList,
      List<FilterMenu> categoryFav,
      List<dynamic> selectedCategory) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.04,
      margin: EdgeInsets.only(
        bottom: MediaQuery.of(context).size.height * 0.01,
      ),
      // color: Colors.red,
      child: Row(
        children: [
          Container(
            // color: Colors.blue,
            width: widthScreen * 0.915,
            child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: favList.length,
                itemBuilder: (context, i) {
                  return GestureDetector(
                    onTap: () {
                      context.read<SearchMenu>().searchMenu(
                            categoryFav,
                            categorySelected: favList[i].name,
                            isSearch: false,
                          );

                      _scrollController.animateTo(
                          _scrollController.position.minScrollExtent,
                          duration: const Duration(milliseconds: 100),
                          curve: Curves.fastOutSlowIn);
                      setState(() {
                        countCategoryToDisplay = 1;
                        countMenuToDisplay = maxItemMenu;
                      });
                    },
                    child: Container(
                      // width: MediaQuery.of(context).size.width * 0.25,
                      padding: EdgeInsets.all(
                          MediaQuery.of(context).size.height * 0.01),
                      margin: EdgeInsets.only(
                          left: (i == 0) ? 0 : widthScreen * 0.007,
                          right: (i == favList.length - 1)
                              ? 0
                              : widthScreen * 0.007),
                      height: double.infinity,
                      // color: Colors.blue,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(roundedButton),
                        color: (selectedCategory[1] == favList[i].name)
                            ? selectedColor
                            : buttonColor,
                      ),
                      child: Center(
                          child: defaultText(context, favList[i].name,
                              style: textStyleSelectedCategory(
                                context,
                              ))),
                    ),
                  );
                }),
          )
        ],
      ),
      // child: ListView.builder(itemBuilder: ),
    );
  }

  Future<dynamic> buttonDialog(BuildContext context, String namaPelanggan,
      List<Orders> listOrders, int tableMode, double widthScreen) {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return AnimatedContainer(
            duration: const Duration(milliseconds: 300),
            child: AlertDialog(
              scrollable: true,
              title: (namaPelanggan == '')
                  ? defaultText(context, "Masukkan Nama")
                  : defaultText(context, "Konfirmasi Order"),
              content: SizedBox(
                height: MediaQuery.of(context).size.height * 0.27,
                width: widthScreen * widhtDialog,
                child: Column(
                  children: [
                    Container(
                        height: MediaQuery.of(context).size.height * 0.12,
                        child: (namaPelanggan == '')
                            ? Column(
                                children: [
                                  TextField(
                                    keyboardType: TextInputType.text,
                                    controller: nameController,
                                    style: textStyleNormalFont(context),
                                    decoration: InputDecoration(
                                      hintText: "Nama panggilan",
                                      hintStyle: TextStyle(
                                        color: Colors.grey,
                                        fontSize:
                                            MediaQuery.of(context).size.height *
                                                normalFont,
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                      height:
                                          MediaQuery.of(context).size.height *
                                              0.005),
                                  (tableMode == multiTable)
                                      ? defaultText(context,
                                          "Pesanan yang diinput tidak dapat dibatalkan, Yakin ingin melanjutkan ?",
                                          style: textStyleNormalFont(
                                            context,
                                            font: variantModalFont,
                                          ))
                                      : const Text('')
                                ],
                              )
                            : defaultText(
                                context,
                                "Pesanan yang diinput tidak dapat dibatalkan, Yakin ingin melanjutkan ?",
                                style: textStyleNormalFont(
                                  context,
                                  font: variantModalFont,
                                ),
                              )),
                    SizedBox(height: MediaQuery.of(context).size.height * 0.01),
                    GestureDetector(
                      onTap: () {
                        if (nameController.text != '' || namaPelanggan != '') {
                          checkOut(context, listOrders, nameController.text);
                        } else {
                          EasyLoading.showToast("Nama wajib diisi");
                        }
                      },
                      child: Container(
                        height:
                            MediaQuery.of(context).size.height * heightTombol,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(roundedButton),
                            color: buttonColor),
                        child: Align(
                            child: defaultText(context, "OK",
                                style: textStyleNormalFont(
                                  context,
                                  color: textInButton,
                                ))),
                      ),
                    ),
                    SizedBox(
                      height: MediaQuery.of(context).size.height * 0.02,
                    ),
                    GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                      },
                      child: Container(
                        height:
                            MediaQuery.of(context).size.height * heightTombol,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(roundedButton),
                          color: Colors.transparent,
                        ),
                        child: Align(
                            child: defaultText(context, "Batal",
                                style: textStyleNormalFont(
                                  context,
                                  color: textCancelColor,
                                ))),
                      ),
                    )
                  ],
                ),
              ),
            ),
          );
        });
  }
}
