// 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_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: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 '../../bloc/filter_menu.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.dart';
import 'cat_list.dart';
import 'fav_grid_menu.dart';
import 'fav_list.dart';
import 'package:byod/models/category_list.dart';

import 'menu_list_utama.dart';
import 'shimmer_menu.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<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(
      () {
        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;
        //     });
        //   }
        // }
      },
    );
    _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 = 36;
    double spacerHeight = 20;
    double favListHeight = 35;
    double favItemHeight = 219;
    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;
    double paddingLeftRight = 20;

    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: 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 = [];
                          var nn = {
                            "name": "All",
                            "id": "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));
                            }

                            categoryList = catListTemp;
                          }
                          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);
                            }
                          }
                        }

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

                          return BlocBuilder<SearchMenu, List<dynamic>>(
                            builder: (contextSearch, listSearch) {
                              // if (listSearch[0].isNotEmpty) {
                              //   print(listSearch[0]);
                              // }

                              return BlocBuilder<MenuSelectedBar,
                                  List<dynamic>>(
                                builder: (contextSelectedBarMenu,
                                    listDynamicBarMenu) {
                                  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 (listDynamicBarMenu.length == 2 &&
                                              nameCat.categoryId ==
                                                  listDynamicBarMenu[1]) {
                                            temprSelectedMenu.add(nameCat);
                                          }
                                        }
                                        if (listDynamicBarMenu.length == 2 &&
                                            listDynamicBarMenu[0] == 0) {
                                          categoryMenuAfterSelect =
                                              categoryNonFav;
                                        } else {
                                          categoryMenuAfterSelect =
                                              temprSelectedMenu;
                                        }
                                      } else {
                                        // for (var nameCatSearch
                                        //     in listSearch[0]) {
                                        //   if (listDynamicBarMenu.length == 2) {
                                        //     if (listDynamicBarMenu[1] != "0" &&
                                        //         nameCatSearch.categoryId ==
                                        //             listDynamicBarMenu[1]) {
                                        //       temprSearchMenu
                                        //           .add(nameCatSearch);
                                        //     }
                                        //   }
                                        // }
                                        if (listDynamicBarMenu[1] != "0") {
                                          List<FilterMenu> temprSearchMenu = [];
                                          for (var nameMenuSearch
                                              in listSearch[0]) {
                                            if (listDynamicBarMenu[1] ==
                                                nameMenuSearch.categoryId) {
                                              temprSearchMenu
                                                  .add(nameMenuSearch);
                                            }
                                          }
                                          categoryMenuAfterSelect =
                                              temprSearchMenu;
                                        } else {
                                          categoryMenuAfterSelect =
                                              listSearch[0];
                                        }
                                        // if (listDynamicBarMenu.length == 2 &&
                                        //     listDynamicBarMenu[0] == 0) {
                                        //   categoryMenuAfterSelect =
                                        //       categoryNonFav;
                                        // } else {
                                        //   categoryMenuAfterSelect =
                                        //       temprSelectedMenu;
                                        // }
                                      }

                                      // if (listDynamicBarMenu.length == 2 &&
                                      //     isScrollableMenu == true &&
                                      //     _scrollController.position.pixels ==
                                      //         _scrollController
                                      //             .position.maxScrollExtent &&
                                      //     _scrollMenuItem.position.pixels > 0) {
                                      //   _scrollMenuItem.animateTo(
                                      //     1,
                                      //     duration:
                                      //         Duration(milliseconds: animatedTime),
                                      //     curve: Curves.fastOutSlowIn,
                                      //   );
                                      // }
                                    }
                                  } else {
                                    if (categoryNonFav.isNotEmpty &&
                                        categoryList.isNotEmpty) {
                                      List<FilterMenu> temprSelectedMenu = [];
                                      for (var nameCat in categoryNonFav) {
                                        if (listDynamicBarMenu.length == 2 &&
                                            nameCat.categoryId ==
                                                listDynamicBarMenu[1]) {
                                          temprSelectedMenu.add(nameCat);
                                        }
                                      }
                                      if (listDynamicBarMenu.length == 2 &&
                                          listDynamicBarMenu[0] == 0) {
                                        categoryMenuAfterSelect =
                                            categoryNonFav;
                                      } else {
                                        categoryMenuAfterSelect =
                                            temprSelectedMenu;
                                      }

                                      // if (listDynamicBarMenu.length == 2 &&
                                      //     isScrollableMenu == true &&
                                      //     _scrollController.position.pixels ==
                                      //         _scrollController
                                      //             .position.maxScrollExtent &&
                                      //     _scrollMenuItem.position.pixels > 0) {
                                      //   _scrollMenuItem.animateTo(
                                      //     1,
                                      //     duration:
                                      //         Duration(milliseconds: animatedTime),
                                      //     curve: Curves.fastOutSlowIn,
                                      //   );
                                      // }
                                    }
                                  }

                                  return BlocBuilder<OrdersBloc, List<Orders>>(
                                    builder: (contextOrders, 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,
                                          paddingLeftRight,
                                          appBarHeight,
                                          tableNumber,
                                          userName,
                                          searchFieldHeight,
                                          spacerHeight,
                                          favListHeight,
                                          favItemHeight,
                                          spacerAboveCat,
                                          spacerAboveCatList,
                                          catListHeight,
                                          spacerAboveMenuItem,
                                          heightLeft,
                                          totalItem,
                                          listOrders,
                                          totalHarga,
                                          tableMode,
                                        ),
                                        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(),
            ),
          ),
        );
      },
    );
  }

  Stack coreHome(
      BuildContext context,
      double widthScreen,
      double maxWidthScreen,
      double paddingLeftRight,
      double appBarHeight,
      String tableNumber,
      String userName,
      double searchFieldHeight,
      double spacerHeight,
      double favListHeight,
      double favItemHeight,
      double spacerAboveCat,
      double spacerAboveCatList,
      double catListHeight,
      double spacerAboveMenuItem,
      double heightLeft,
      int totalItem,
      List<Orders> listOrders,
      int totalHarga,
      int tableMode) {
    return Stack(
      children: [
        Container(
          width: widthScreen,
          height: MediaQuery.of(context).size.height,
          padding: EdgeInsets.symmetric(horizontal: paddingLeftRight),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              customAppBar(
                context,
                paddingLeftRight,
                appBarHeight,
                tableNumber,
                userName,
              ),
              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: 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,
                      ),
                    ),
                    // SliverToBoxAdapter(
                    //   child: Container(
                    //     height: heightLeft,
                    //     child: ListView.builder(
                    //       controller:
                    //           (isScrollableMenu) ? _scrollMenuItem : null,
                    //       // itemScrollController:
                    //       //     (isScrollableMenu) ? scrollMenuItemList : null,
                    //       physics: (!isScrollableMenu)
                    //           ? const NeverScrollableScrollPhysics()
                    //           : null,
                    //       shrinkWrap: (isScrollableMenu) ? true : false,
                    //       // itemCount: (categoryMenuAfterSelect.length) >
                    //       //         countMenuToDisplay
                    //       //     ? countMenuToDisplay
                    //       //     : categoryMenuAfterSelect.length,
                    //       itemCount: categoryMenuAfterSelect.length,
                    //       itemBuilder: (context, i) {
                    //         return MenuListUtama(
                    //           categoryNonFav: categoryMenuAfterSelect,
                    //           i: i,
                    //         );
                    //       },
                    //     ),
                    //   ),
                    // ),
                    SliverList(
                      delegate: SliverChildBuilderDelegate(
                        (context, index) {
                          return MenuListUtama(
                            categoryNonFav: categoryMenuAfterSelect,
                            i: index,
                            widthScreen: widthScreen,
                            scrollController: _scrollController,
                          );
                        },
                        childCount: categoryMenuAfterSelect.length,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        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,
                )
              : const SizedBox(
                  key: Key('ButtonBottomCart'),
                ),
        )
      ],
    );
  }

  Container searchField(
      double searchFieldHeight, List<FilterMenu> categoryNonFav) {
    return Container(
      margin: const EdgeInsets.only(bottom: 5),
      height: searchFieldHeight,
      child: TextField(
        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,
          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) {
    String itemString;
    if (totalItem > 1) {
      itemString = '$totalItem Items';
    } else {
      itemString = '$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: textStyleNormalFont(context),
                              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: MediaQuery.of(context).size.width,
              height: 61,
              decoration: BoxDecoration(
                color: buttonColor,
                borderRadius: const BorderRadius.only(
                  topRight: Radius.circular(20),
                  topLeft: Radius.circular(10),
                ),
              ),
              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,
                          ),
                          const Image(
                              width: 20,
                              height: 20,
                              image: AssetImage('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: MediaQuery.of(context).size.width - 157,
                decoration: BoxDecoration(
                  color: buttonColor,
                  borderRadius: const BorderRadius.only(
                    topLeft: Radius.circular(20),
                  ),
                ),
                child: Align(
                  alignment: Alignment.centerLeft,
                  child: defaultText(
                    context,
                    itemString,
                    style: textCountItem(),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Container customAppBar(BuildContext context, double paddingLeftRight,
      double appBarHeight, String tableNumber, String userName) {
    String barName;
    if (userName != '') {
      barName = 'Meja $tableNumber - $userName';
    } else {
      barName = "Meja $tableNumber";
    }
    return Container(
        height: appBarHeight,
        child: Row(
          children: [
            defaultText(
              context,
              barName,
              style: tableNameStyle(),
            ),
            const Spacer(),
            GestureDetector(
              onTap: () {
                setState(() {
                  isSearchActive = !isSearchActive;
                });
              },
              child: const Image(
                image: AssetImage('assets/icons/search.png'),
                height: 20,
                width: 20,
              ),
            ),
            const SizedBox(
              width: 16,
            ),
            GestureDetector(
              onTap: () {
                Navigator.push(
                    context, MaterialPageRoute(builder: (_) => ViewBill()));
              },
              child: const Image(
                image: AssetImage('assets/icons/book.png'),
                height: 20,
                width: 20,
              ),
            ),
          ],
        ));
  }

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

  // AnimatedSwitcher seearchField(BuildContext context) {
  //   return AnimatedSwitcher(
  //     duration: const Duration(milliseconds: 500),
  //     transitionBuilder: (Widget child, Animation<double> animation) {
  //       return ScaleTransition(scale: animation, child: child);
  //     },
  //     child: TextField(
  //       key: const Key('SearchField'),
  //       decoration: InputDecoration(
  //         focusedBorder: OutlineInputBorder(
  //           borderSide: BorderSide(
  //             width: 1,
  //             color: buttonColor,
  //           ),
  //         ),
  //         prefixIcon: const Image(
  //           image: AssetImage('assets/icons/search.png'),
  //           height: 20,
  //           width: 20,
  //         ),
  //         hintText: 'Example: nasi',
  //         border: OutlineInputBorder(
  //           borderRadius: BorderRadius.circular(6),
  //         ),
  //       ),
  //     ),
  //   );
  // }
}

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 CustomClipPath extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    // buat clipnya di https://shapemaker.web.app/#/

    Path path0 = Path();
    path0.moveTo(0, 0);
    path0.lineTo(0, size.height);
    path0.lineTo(size.width, size.height);
    path0.quadraticBezierTo(size.width, size.height * 0.6250000, size.width,
        size.height * 0.5042857);
    path0.cubicTo(
        size.width * 0.8616667,
        size.height * 0.4364286,
        size.width * 0.9810417,
        size.height * 0.0007143,
        size.width * 0.7191667,
        0);
    path0.quadraticBezierTo(size.width * 0.5468750, 0, 0, 0);
    path0.close();
    return path0;
  }

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