// ignore_for_file: sized_box_for_whitespace

import 'package:byod/bloc/branch_exist.dart';
import 'package:byod/bloc/fav_selected_bar.dart';
import 'package:byod/bloc/menu_selected_bar.dart';
import 'package:byod/bloc/order_bloc.dart';
import 'package:byod/bloc/search_active.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/filter_menu.dart';
import 'package:byod/models/orders.dart';
import 'package:byod/ui/home/menu_list_utama.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
import 'package:sliver_tools/sliver_tools.dart';

import '../../bloc/filter_menu.dart';
import '../../helper/mq.dart';
import '../../helper/widget/button_dialog.dart';
import '../../main.dart';
import '../../models/fav_group.dart';
import '../checkout/checkout.dart';
import '../checkout/fuction.dart';
import '../screen_responsive.dart';
import '../viewbill/view_bill_new.dart';
import 'cat_list.dart';
import 'fav_grid_menu.dart';
import 'fav_list.dart';
import 'package:byod/models/category_list.dart';
import 'shimmer_menu_new.dart';

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

  @override
  State<NewHome2> createState() => _NewHome2State();
}

class _NewHome2State extends State<NewHome2> {
  // bool isSearchActive = false;
  bool isFirstLoad = true;
  final searchController = TextEditingController();
  final _scrollController = ScrollController();
  final _scrollFavItem = ScrollController();
  // final _scrollMenuItem = ScrollController();
  final scrollMenuItemList = ItemScrollController();

  late bool isScrollableMenu = false;
  // final double positionCustomScrollViewFixed = 345.5 - 10;
  // final double positionCustomScrollViewSearchFalseFixed = 349.5 - 10;

  late List<FilterMenu> allMenu = [];
  late List<FilterMenu> allMenuFav = [];

  List<CategoryList> categoryList = [];
  List<CategoryList> categoryListMenu = [];
  List<FavoriteGroup> favList = [];
  List<FilterMenu> categoryNonFav = [];
  List<FilterMenu> categoryFav = [];
  List<FilterMenu> categoryFavAfterSelect = [];
  List<FilterMenu> categoryMenuAfterSelect = [];

  late int countMenuToDisplay = maxItemMenu;
  late int countMenuFavToDisplay = maxItemMenuFav;

  @override
  void initState() {
    _scrollController.addListener(
      () {
        if (isFirstLoad) {
          setState(() {
            isFirstLoad = false;
          });
        }

        // double positionCustomScrollView = _scrollController.position.pixels;
        // print(positionCustomScrollView);
        // if (_scrollController.position.pixels >=
        //     (_scrollController.position.maxScrollExtent - 100)) {}
        // double positionCustomScrollView = _scrollController.position.pixels;
        // double positionCustomScrollViewMax =
        //     _scrollController.position.maxScrollExtent;
        // if (isSearchActive) {
        // if (positionCustomScrollView >= positionCustomScrollViewMax - 50) {
        //   setState(() {
        //     isScrollableMenu = true;
        //   });
        // } else {
        //   setState(() {
        //     isScrollableMenu = false;
        //   });
        // }
        // } else {
        //   if (positionCustomScrollView >=
        //       positionCustomScrollViewSearchFalseFixed) {
        //     setState(() {
        //       isScrollableMenu = true;
        //     });
        //   } else {
        //     setState(() {
        //       isScrollableMenu = false;
        //     });
        //   }
        // }
      },
    );

    runMqTT(context);
    _scrollFavItem.addListener(() {
      double positionMenuFavScroll = _scrollFavItem.position.pixels;
      double positionMenuFavMax = _scrollFavItem.position.maxScrollExtent;
      if (positionMenuFavScroll >= positionMenuFavMax - 50) {
        if (allMenuFav.length >= countMenuFavToDisplay) {
          _getMoreDataFav(countMenuFavToDisplay, allMenuFav);
        }
      }
    });
    // _scrollMenuItem.addListener(() {
    //   double positionMenuItemScrollView = _scrollMenuItem.position.pixels;

    //   double positionMenuItemScrollViewMin =
    //       _scrollMenuItem.position.minScrollExtent;
    //   double positionMenuItemScrollViewMax =
    //       _scrollMenuItem.position.maxScrollExtent;
    //   if (positionMenuItemScrollView == positionMenuItemScrollViewMin &&
    //       _scrollController.position.pixels ==
    //           _scrollController.position.maxScrollExtent) {
    //     setState(() {
    //       isScrollableMenu = false;
    //     });
    //   }
    //   if (positionMenuItemScrollView >= positionMenuItemScrollViewMax - 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;
  //     }
  //   });
  // }

  // scrollToMenuCat(id) {
  //   int indexCategory = categoryNonFav.indexWhere((categoryNonFav) =>
  //       categoryNonFav.categoryId == id && categoryNonFav.type == typeCategory);
  //   if (indexCategory != -1 && isScrollableMenu) {
  //     scrollMenuItemList.jumpTo(index: indexCategory);
  //   }
  // }

  _getMoreDataFav(int menuToDisplay, List<FilterMenu> allMenuFav) {
    setState(() {
      if ((allMenuFav.length - countMenuFavToDisplay) > maxItemMenuFav) {
        countMenuFavToDisplay += maxItemMenuFav;
      } else {
        countMenuFavToDisplay = allMenuFav.length;
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    // double heightTotal = MediaQuery.of(context).size.height;
    double appBarHeight = 40;
    double searchFieldHeight = 50;
    double spacerHeight = 20;
    double favListHeight = 35;
    double favItemHeight = 227;
    double spacerAboveCat = 16;
    // double categoryFont = 14;
    double spacerAboveCatList = 42;
    double catListHeight = 51;
    double spacerAboveMenuItem = 25;
    // double heightLeft = (isSearchActive)
    //     ? heightTotal -
    //         appBarHeight -
    //         searchFieldHeight -
    //         spacerHeight -
    //         favListHeight -
    //         categoryFont -
    //         spacerAboveCatList
    //     : heightTotal -
    //         appBarHeight -
    //         favListHeight -
    //         categoryFont -
    //         spacerAboveCatList;

    int tableMode = prefs.getInt('table_mode') ?? defaultTable;
    String tableNumber = prefs.getString("table_number") ?? "";
    String userName = prefs.getString("userName") ?? "";
    double widthScreen = responsiveWidthScreen(context);
    double maxWidthScreen = getMaxWidthScreen(context, useResponsive);
    return BlocBuilder<BranchExist, String>(
      builder: (contextBracnhExist, restoran) {
        void onTapOkPop() {
          Navigator.pop(context, true);
        }

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

        return WillPopScope(
          onWillPop: () async {
            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: GestureDetector(
              onTap: () {
                FocusScopeNode currentFocus = FocusScope.of(context);

                if (!currentFocus.hasPrimaryFocus) {
                  currentFocus.unfocus();
                }
              },
              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> categoryFavTemp = [];
                            List<FilterMenu> categoryNonFavTemp = [];

                            for (var menu in categoryDefault) {
                              if (!menu.isFavMenu) {
                                categoryNonFavTemp.add(menu);
                              } else {
                                categoryFavTemp.add(menu);
                              }
                            }
                            categoryNonFav = categoryNonFavTemp;
                            categoryFav = categoryFavTemp;

                            allMenu = categoryNonFav;
                            allMenuFav = categoryFav;
                            List<CategoryList> catListTemp = [];
                            List<CategoryList> catListTempMenu = [];
                            var nn = {
                              "name": "All",
                              "id": "",
                              "offset": 0,
                            }; // all dulu, biar ada bisa klik all
                            catListTemp
                                .add(CategoryList.createCategoryList(nn));

                            for (var nameCat in categoryNonFav) {
                              if (nameCat.type == typeCategory) {
                                var n = {
                                  "id": nameCat.id,
                                  "name": nameCat.categoryName,
                                };
                                catListTemp
                                    .add(CategoryList.createCategoryList(n));
                                catListTempMenu
                                    .add(CategoryList.createCategoryList(n));
                              }
                            }
                            categoryList = catListTemp;
                            categoryListMenu = catListTempMenu;
                            List<FavoriteGroup> favGroupTemp = [];
                            for (var nameFav in categoryFav) {
                              if (nameFav.type == typeCategory) {
                                var nfav = {
                                  "name": nameFav.categoryName,
                                  "id": nameFav.id
                                };
                                favGroupTemp.add(FavoriteGroup.add(nfav));
                              }
                            }
                            favList = favGroupTemp;
                            if (isFirstLoad) {
                              if (favList.isNotEmpty) {
                                context
                                    .read<FavSelectedBar>()
                                    .selectedBarFav(0, favList[0].id);
                              }
                              if (categoryList.isNotEmpty) {
                                context
                                    .read<MenuSelectedBar>()
                                    .selectedBarMenu(0, categoryList[0].id);
                              }
                            }
                          } else {
                            return ScreenResponsive(
                              widget: const ShimmerMenuNew(),
                              widthScreen: MediaQuery.of(context).size.width,
                              isCoreLayout: true,
                            );
                          }

                          return BlocBuilder<FavSelectedBar,
                                  Map<String, dynamic>>(
                              builder: (contextFavSelectedBar, listDynamicBar) {
                            if (categoryFav.isNotEmpty && favList.isNotEmpty) {
                              List<FilterMenu> temporSelectedFav = [];
                              for (var nameFav in categoryFav) {
                                if (nameFav.type == typeMenu &&
                                    nameFav.favGroupId ==
                                        listDynamicBar['id']) {
                                  temporSelectedFav.add(nameFav);
                                }
                              }
                              categoryFavAfterSelect = temporSelectedFav;
                            }

                            return BlocBuilder<SearchActive, bool>(
                              builder: (contextSearch, isSearchActive) {
                                return BlocBuilder<SearchMenu, List<dynamic>>(
                                  builder: (contextSearchActive, listSearch) {
                                    return BlocBuilder<MenuSelectedBar,
                                        Map<String, dynamic>>(
                                      builder: (contextSelectedBarMenu,
                                          listDynamicBarMenu) {
                                        List<CategoryList> catListMenuTmp = [];
                                        if (isSearchActive) {
                                          if (categoryNonFav.isNotEmpty &&
                                              categoryList.isNotEmpty) {
                                            if (listSearch[0].length == 1 &&
                                                listSearch[0][0].id ==
                                                    'start') {
                                              List<FilterMenu>
                                                  temprSelectedMenu = [];
                                              for (var nameCat
                                                  in categoryNonFav) {
                                                if (nameCat.categoryId ==
                                                    listDynamicBarMenu['id']) {
                                                  temprSelectedMenu
                                                      .add(nameCat);
                                                }
                                              }
                                              if (listDynamicBarMenu['index'] ==
                                                  0) {
                                                categoryMenuAfterSelect =
                                                    categoryNonFav;
                                              } else {
                                                categoryMenuAfterSelect =
                                                    temprSelectedMenu;
                                              }
                                            } else {
                                              if (listDynamicBarMenu['id'] !=
                                                  "") {
                                                List<FilterMenu>
                                                    temprSearchMenu = [];
                                                for (var nameMenuSearch
                                                    in listSearch[0]) {
                                                  if (listDynamicBarMenu[
                                                          'id'] ==
                                                      nameMenuSearch
                                                          .categoryId) {
                                                    temprSearchMenu
                                                        .add(nameMenuSearch);
                                                  }
                                                }
                                                categoryMenuAfterSelect =
                                                    temprSearchMenu;
                                              } else {
                                                categoryMenuAfterSelect =
                                                    listSearch[0];
                                              }
                                            }
                                          }
                                          for (var nameCatAfterSelect
                                              in categoryMenuAfterSelect) {
                                            if (nameCatAfterSelect.type ==
                                                typeCategory) {
                                              var nn = {
                                                "id": nameCatAfterSelect.id,
                                                "name": nameCatAfterSelect
                                                    .categoryName,
                                              };
                                              catListMenuTmp.add(CategoryList
                                                  .createCategoryList(nn));
                                            }
                                          }
                                          categoryListMenu = catListMenuTmp;
                                        } else {
                                          if (categoryNonFav.isNotEmpty &&
                                              categoryList.isNotEmpty) {
                                            List<FilterMenu> temprSelectedMenu =
                                                [];

                                            for (var nameCat
                                                in categoryNonFav) {
                                              if (nameCat.categoryId ==
                                                  listDynamicBarMenu['id']) {
                                                temprSelectedMenu.add(nameCat);
                                              }
                                            }
                                            if (listDynamicBarMenu['index'] ==
                                                0) {
                                              categoryMenuAfterSelect =
                                                  categoryNonFav;
                                            } else {
                                              categoryMenuAfterSelect =
                                                  temprSelectedMenu;
                                            }

                                            for (var nameCatAfterSelect
                                                in categoryMenuAfterSelect) {
                                              if (nameCatAfterSelect.type ==
                                                  typeCategory) {
                                                var nn = {
                                                  "id": nameCatAfterSelect.id,
                                                  "name": nameCatAfterSelect
                                                      .categoryName,
                                                };
                                                catListMenuTmp.add(CategoryList
                                                    .createCategoryList(nn));
                                              }
                                            }
                                            categoryListMenu = catListMenuTmp;
                                          }
                                        }

                                        return BlocBuilder<OrdersBloc,
                                            List<Orders>>(
                                          builder: (context, listOrders) {
                                            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 ScreenResponsive(
                                              widget: coreHome(
                                                context,
                                                widthScreen,
                                                maxWidthScreen,
                                                appBarHeight,
                                                tableNumber,
                                                userName,
                                                searchFieldHeight,
                                                spacerHeight,
                                                favListHeight,
                                                favItemHeight,
                                                spacerAboveCat,
                                                spacerAboveCatList,
                                                catListHeight,
                                                spacerAboveMenuItem,
                                                totalItem,
                                                listOrders,
                                                totalHarga,
                                                tableMode,
                                                isSearchActive,
                                              ),
                                              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: const ShimmerMenuNew(),
                                        widthScreen:
                                            MediaQuery.of(context).size.width,
                                        isCoreLayout: true,
                                      )
                                    : const SizedBox(),
              ),
            ),
          ),
        );
      },
    );
  }

  Stack coreHome(
    BuildContext context,
    double widthScreen,
    double maxWidthScreen,
    double appBarHeight,
    String tableNumber,
    String userName,
    double searchFieldHeight,
    double spacerHeight,
    double favListHeight,
    double favItemHeight,
    double spacerAboveCat,
    double spacerAboveCatList,
    double catListHeight,
    double spacerAboveMenuItem,
    int totalItem,
    List<Orders> listOrders,
    int totalHarga,
    int tableMode,
    bool isSearchActive,
  ) {
    String logoUrl = prefs.getString("logoUrl") ?? "";
    return Stack(
      children: [
        Container(
          width: widthScreen,
          height: MediaQuery.of(context).size.height,
          padding: const EdgeInsets.symmetric(horizontal: paddingLeftRight),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // customAppBar(
              //   context,
              //   paddingLeftRight,
              //   appBarHeight,
              //   tableNumber,
              //   userName,
              //   isSearchActive,
              // ),
              // SizedBox(
              //   height: (isSearchActive) ? 16 : 20,
              // ),
              // AnimatedSwitcher(
              //   duration: Duration(milliseconds: animatedTime),
              //   transitionBuilder: (Widget child, Animation<double> animation) {
              //     return ScaleTransition(scale: animation, child: child);
              //   },
              //   child: (isSearchActive)
              //       ? searchField(
              //           searchFieldHeight,
              //           categoryNonFav,
              //         )
              //       : const SizedBox(
              //           key: Key('SearchField'),
              //         ),
              // ),
              Expanded(
                child: CustomScrollView(
                  controller: _scrollController,
                  slivers: [
                    SliverToBoxAdapter(
                      child: (logoUrl != '')
                          ? Container(
                              padding: const EdgeInsets.only(
                                top: 16,
                              ),
                              child: Row(
                                children: [
                                  const Spacer(),
                                  Container(
                                    width: 209,
                                    height: 80,
                                    child: Image(
                                      width: 209,
                                      height: 80,
                                      fit: BoxFit.fill,
                                      image: NetworkImage(logoUrl),
                                    ),
                                  ),
                                  const Spacer(),
                                ],
                              ),
                            )
                          : const SizedBox(),
                    ),
                    SliverPersistentHeader(
                      pinned: true,
                      delegate: DelegateAppBar(
                        appBarHeight + searchFieldHeight,
                        customAppBar(
                          context,
                          paddingLeftRight,
                          appBarHeight + searchFieldHeight,
                          tableNumber,
                          userName,
                          isSearchActive,
                        ),
                      ),
                    ),
                    SliverPersistentHeader(
                      pinned: true,
                      delegate: DelegateSearchField(
                        isSearchActive,
                        searchFieldHeight,
                        searchField(
                          searchFieldHeight,
                          categoryNonFav,
                        ),
                      ),
                    ),
                    SliverToBoxAdapter(
                      child: SizedBox(
                        height: (isSearchActive) ? spacerHeight : 0,
                      ),
                    ),
                    SliverToBoxAdapter(
                      child: (favList.isNotEmpty)
                          ? Container(
                              height: favListHeight,
                              child: FavoriteList(
                                favoriteList: favList,
                              ),
                            )
                          : const SizedBox(),
                    ),
                    SliverToBoxAdapter(
                      child: SizedBox(
                        height: (categoryFavAfterSelect.isNotEmpty) ? 13.5 : 0,
                      ),
                    ),
                    SliverToBoxAdapter(
                      child: (categoryFavAfterSelect.isNotEmpty)
                          ? Container(
                              height: favItemHeight,
                              child: ListView.builder(
                                controller: _scrollFavItem,
                                scrollDirection: Axis.horizontal,
                                itemCount: (categoryFavAfterSelect.length) >
                                        countMenuFavToDisplay
                                    ? countMenuFavToDisplay
                                    : categoryFavAfterSelect.length,
                                itemBuilder: (context, i) {
                                  double paddingLeftRigthGrid = 9;
                                  double widthGrid = 136;
                                  return FavGridMenu(
                                    categoryFavAfterSelect:
                                        categoryFavAfterSelect,
                                    widthGrid: widthGrid,
                                    paddingLeftRigthGrid: paddingLeftRigthGrid,
                                    i: i,
                                  );
                                },
                              ),
                            )
                          : const SizedBox(),
                    ),
                    SliverToBoxAdapter(
                      child: SizedBox(
                        height: (categoryFavAfterSelect.isNotEmpty)
                            ? spacerAboveCat
                            : 0,
                      ),
                    ),
                    SliverToBoxAdapter(
                      child: (categoryFavAfterSelect.isNotEmpty)
                          ? defaultText(
                              context,
                              'Category',
                              style: categoryStyle(),
                            )
                          : const SizedBox(),
                    ),
                    SliverToBoxAdapter(
                      child: SizedBox(
                        height: (categoryFavAfterSelect.isNotEmpty)
                            ? spacerAboveCatList
                            : 0,
                      ),
                    ),
                    SliverPersistentHeader(
                      pinned: true,
                      delegate: Delegate(
                        catListHeight,
                        categoryList,
                        _scrollController,
                        favList,
                      ),
                    ),
                    SliverToBoxAdapter(
                      child: SizedBox(
                        height: spacerAboveMenuItem,
                      ),
                    ),

                    for (int i = 0; i < categoryListMenu.length; i++)
                      MultiSliver(
                        pushPinnedChildren: true,
                        children: [
                          SliverPinnedHeader(
                            child: Container(
                              color: backgroundColor,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  defaultText(
                                    context,
                                    categoryListMenu[i].name,
                                    maxLines: 1,
                                    overFlow: TextOverflow.ellipsis,
                                    style: categoryNameStyle(),
                                  ),
                                  const Divider(
                                    thickness: 0.1,
                                    color: textColorBlack,
                                  ),
                                ],
                              ),
                            ),
                          ),
                          SliverList(
                            delegate:
                                SliverChildBuilderDelegate((context, index) {
                              return MenuListUtama(
                                categoryNonFav: categoryMenuAfterSelect,
                                i: index,
                                widthScreen: widthScreen,
                                scrollController: _scrollController,
                                idCategory: categoryListMenu[i].id,
                              );
                            }, childCount: categoryMenuAfterSelect.length),
                          ),
                        ],
                      ),
                    // SliverList(
                    //   delegate: SliverChildBuilderDelegate(
                    //     (context, index) {
                    //       return MenuListUtama(
                    //         categoryNonFav: categoryMenuAfterSelect,
                    //         i: index,
                    //         widthScreen: widthScreen,
                    //         scrollController: _scrollController,
                    //       );
                    //     },
                    //     childCount: categoryMenuAfterSelect.length,
                    //   ),
                    // ),
                  ],
                ),
              ),
            ],
          ),
        ),
        Container(
          width: widthScreen,
          child: AnimatedSwitcher(
            duration: Duration(milliseconds: animatedTime),
            transitionBuilder: (Widget child, Animation<double> animation) {
              return ScaleTransition(scale: animation, child: child);
            },
            child: (totalItem > 0)
                ? goTocheckOut(
                    context,
                    listOrders,
                    paddingLeftRight,
                    totalItem,
                    totalHarga,
                    tableMode,
                    userName,
                    widthScreen,
                  )
                : const SizedBox(
                    key: Key('ButtonBottomCart'),
                  ),
          ),
        )
      ],
    );
  }

  Container searchField(
      double searchFieldHeight, List<FilterMenu> categoryNonFav) {
    return Container(
      padding: const EdgeInsets.only(bottom: 10),
      height: searchFieldHeight,
      color: backgroundColor,
      child: TextField(
        autofocus: true,
        textAlignVertical: TextAlignVertical.center,
        onChanged: (sarchValue) {
          context.read<SearchMenu>().searchMenu(
                categoryNonFav,
                keyword: sarchValue.toString(),
                isSearch: true,
              );
        },
        key: const Key('SearchField'),
        style: TextStyle(
          color: Colors.black,
          fontFamily: fontFamily,
          fontSize: 15,
        ),
        decoration: InputDecoration(
          filled: true,
          fillColor: Colors.white,
          contentPadding: const EdgeInsets.symmetric(vertical: 10),
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(
              width: 1,
              color: Colors.grey.withOpacity(0.8),
            ),
          ),
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              width: 1,
              color: buttonColor,
            ),
          ),
          prefixIcon: Image(
            image: const AssetImage('assets/icons/search.png'),
            color: Colors.grey.withOpacity(0.8),
            height: 20,
            width: 20,
          ),
          hintText: 'Example: nasi',
          hintStyle: TextStyle(
            color: Colors.grey.withOpacity(0.8),
            fontFamily: fontFamily,
            fontSize: 10,
          ),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(6),
          ),
        ),
      ),
    );
  }

  GestureDetector goTocheckOut(
      BuildContext context,
      List<Orders> listOrders,
      double paddingLeftRight,
      int totalItem,
      int totalHarga,
      int tableMode,
      String namaPelanggan,
      double widthScreen) {
    String totalItemString;
    if (totalItem > 1) {
      totalItemString = '$totalItem Items';
    } else {
      totalItemString = '$totalItem Item';
    }
    final nameController = TextEditingController();
    return GestureDetector(
      onTap: () {
        if (tableMode == singleTable) {
          if (namaPelanggan != '') {
            checkOut(context, listOrders, namaPelanggan);
          } else {
            showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AnimatedContainer(
                    duration: const Duration(milliseconds: 300),
                    child: AlertDialog(
                      scrollable: true,
                      title: defaultText(
                        context,
                        "Masukkan Nama",
                        style: modalNamaHeader(),
                      ),
                      content: SizedBox(
                        height: 216,
                        width: 303,
                        child: Column(
                          children: [
                            TextField(
                              keyboardType: TextInputType.text,
                              controller: nameController,
                              style: const TextStyle(
                                fontFamily: 'OpenSans',
                                fontSize: 14,
                                color: textColorBlack,
                              ),
                              decoration: const InputDecoration(
                                labelText: 'Nama panggilan',
                                labelStyle: TextStyle(
                                  fontFamily: 'OpenSans',
                                  fontSize: 14,
                                  color: textColorModalHeaderNama,
                                ),
                              ),
                            ),
                            const SizedBox(
                              height: 47,
                            ),
                            GestureDetector(
                              onTap: () {
                                if (nameController.text != '' ||
                                    namaPelanggan != '') {
                                  checkOut(
                                      context, listOrders, nameController.text);
                                } else {
                                  EasyLoading.showToast("Nama wajib diisi");
                                }
                              },
                              child: Container(
                                height: 43,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(31),
                                    color: buttonColor),
                                child: Center(
                                  child: defaultText(
                                    context,
                                    "Simpan",
                                    style: simpanButtonNote(
                                      font: 14,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                            const SizedBox(
                              height: 20,
                            ),
                            GestureDetector(
                              onTap: () {
                                Navigator.pop(context);
                              },
                              child: Container(
                                height: 43,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(31),
                                  color: Colors.transparent,
                                ),
                                child: Center(
                                  child: defaultText(
                                    context,
                                    "Batal",
                                    style: simpanButtonNote(
                                      font: 14,
                                      fontWeight: FontWeight.w600,
                                      color: textColorRed,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                });
          }
        } else {
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => const CheckOut()));
        }
      },
      child: Stack(
        key: const Key('ButtonBottomCart'),
        children: [
          Positioned(
            bottom: 0,
            child: Container(
              width: widthScreen,
              height: 61,
              decoration: BoxDecoration(
                color: buttonColor,
                borderRadius: const BorderRadius.only(
                  topRight: Radius.circular(20),
                  topLeft: Radius.circular(10),
                  // bottomLeft: Radius.circular(50),
                  // bottomRight: Radius.circular(50),
                ),
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.only(left: paddingLeftRight),
                      child: defaultText(
                        context,
                        "Rp ${formatNumber().format(totalHarga)}",
                        style: textAmountButtonBottomCart(),
                      ),
                    ),
                  ),
                  Container(
                    width: 134,
                    height: 36,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(28),
                      color: Colors.white,
                    ),
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 26, vertical: 8),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          defaultText(
                            context,
                            "Pesan",
                            style: addButtonBottomCart(
                              color: buttonColor,
                            ),
                          ),
                          const SizedBox(
                            width: 7,
                          ),
                          Image(
                            width: 20,
                            height: 20,
                            image: AssetImage((isExcelso)
                                ? 'assets/icons/cart-gold.png'
                                : 'assets/icons/cart.png'),
                          )
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(
                    width: 23,
                  )
                ],
              ),
            ),
          ),
          Positioned(
            bottom: 40,
            left: 0,
            child: ClipPath(
              clipper: CustomClipPath(),
              child: Container(
                padding: EdgeInsets.only(
                  left: paddingLeftRight,
                ),
                height: 43,
                width: widthScreen - 157,
                decoration: BoxDecoration(
                  color: buttonColor,
                  borderRadius: const BorderRadius.only(
                    topLeft: Radius.circular(20),
                    bottomRight: Radius.circular(20),
                  ),
                ),
                child: Align(
                  alignment: Alignment.centerLeft,
                  child: defaultText(
                    context,
                    totalItemString,
                    style: textCountItem(),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Container customAppBar(
      BuildContext context,
      double paddingLeftRight,
      double appBarHeight,
      String tableNumber,
      String userName,
      bool isSearchActive) {
    String barName;
    if (userName != '') {
      barName = 'Meja $tableNumber - $userName';
    } else {
      barName = "Meja $tableNumber";
    }
    return Container(
        padding: const EdgeInsets.only(top: 10),
        height: appBarHeight,
        color: backgroundColor,
        child: Row(
          children: [
            defaultText(
              context,
              barName,
              style: tableNameStyle(),
            ),
            const Spacer(),
            GestureDetector(
              onTap: () {
                context.read<SearchActive>().searchClick(isSearchActive);
                context.read<MenuSelectedBar>().selectedBarMenu(0, '');
                context.read<SearchMenu>().searchMenu(
                      categoryNonFav,
                      keyword: '',
                      isSearch: true,
                    );
                _scrollController.animateTo(
                  (favList.isNotEmpty)
                      ? heighScrollWithImage
                      : imageHeight, // 371 sudah dihituing pixelnya untuk awal banget dari menu item
                  duration: const Duration(milliseconds: 500),
                  curve: Curves.fastOutSlowIn,
                );
              },
              child: const Image(
                image: AssetImage('assets/icons/search.png'),
                height: 24,
                width: 24,
              ),
            ),
            const SizedBox(
              width: 16,
            ),
            GestureDetector(
              onTap: () {
                // Navigator.push(
                //     context, MaterialPageRoute(builder: (_) => ViewBill()));
                Navigator.push(context,
                    MaterialPageRoute(builder: (_) => const ViewBillNew()));
              },
              child: const Image(
                image: AssetImage('assets/icons/book.png'),
                height: 24,
                width: 24,
              ),
            ),
          ],
        ));
  }

  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),
          )
        ],
      ),
    );
  }
}

class Delegate extends SliverPersistentHeaderDelegate {
  final double catListHeight;
  final ScrollController scrollController;
  // final ScrollController scrollControllerMenu;
  final List<CategoryList> categoryList;
  final List<FavoriteGroup> favList;
  Delegate(
    this.catListHeight,
    this.categoryList,
    this.scrollController,
    this.favList,
    // this.scrollControllerMenu,
  );
  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: backgroundColor,
      height: catListHeight,
      child: CategoryListHome(
        categoryList: categoryList,
        scrollController: scrollController,
        favList: favList,
        // scrollControllerMenu: scrollControllerMenu,
      ),
    );
  }

  @override
  double get maxExtent => catListHeight;

  @override
  double get minExtent => catListHeight;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}

class DelegateAppBar extends SliverPersistentHeaderDelegate {
  final double appBarHeight;
  final Widget customAppBar;
  DelegateAppBar(
    this.appBarHeight,
    this.customAppBar,
  );
  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return customAppBar;
  }

  @override
  double get maxExtent => appBarHeight;

  @override
  double get minExtent => appBarHeight;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}

class DelegateSearchField extends SliverPersistentHeaderDelegate {
  final bool isSearchActive;
  final double searchFieldHeight;
  final Widget searchField;
  DelegateSearchField(
      this.isSearchActive, this.searchFieldHeight, this.searchField);
  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return AnimatedSwitcher(
      duration: Duration(milliseconds: animatedTime),
      transitionBuilder: (Widget child, Animation<double> animation) {
        return ScaleTransition(scale: animation, child: child);
      },
      child: (isSearchActive)
          ? searchField
          : const SizedBox(
              key: Key('SearchField'),
            ),
    );
  }

  @override
  double get maxExtent => (isSearchActive) ? searchFieldHeight : 0;

  @override
  double get minExtent => (isSearchActive) ? searchFieldHeight : 0;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}

class CustomClipPath extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    // buat clipnya di https://shapemaker.web.app/#/

    double w = size.width;
    Path path0 = Path();
    path0.moveTo(0, 0);
    path0.lineTo(0, size.height);
    path0.lineTo(w, size.height);
    path0.quadraticBezierTo(
        w * 1.0004167, size.height * 0.6267857, w, size.height * 0.5985714);
    path0.cubicTo(w * 0.9452083, size.height * 0.4360714, w * 0.9633333,
        size.height * 0.3653571, w * 0.9500000, size.height * 0.2142857);
    path0.quadraticBezierTo(
        w * 0.9337500, size.height * 0.0164286, w * 0.8716667, 0);
    path0.lineTo(0, 0);
    path0.close();
    return path0;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return false;
  }
}
