// 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/helper/helper.dart';
import 'package:byod/helper/widget/style.dart';
import 'package:byod/models/filter_menu.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../bloc/filter_menu.dart';
import '../../helper/widget/button_dialog.dart';
import '../../main.dart';
import '../../models/fav_group.dart';
import '../screen_responsive.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 _scrollMenuItem = ScrollController();

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

  late List<FilterMenu> allMenu = [];

  @override
  void initState() {
    _scrollController.addListener(
      () {
        setState(() {
          isFirstLoad = false;
        });
        // if (_scrollController.position.pixels >=
        //     (_scrollController.position.maxScrollExtent - 100)) {}
        double positionCustomScrollView = _scrollController.position.pixels;
        double positionCustomScrollViewMax =
            _scrollController.position.maxScrollExtent;
        // if (isSearchActive) {
        if (positionCustomScrollView >= positionCustomScrollViewMax) {
          setState(() {
            isScrollableMenu = true;
          });
        } else {
          setState(() {
            isScrollableMenu = false;
          });
        }
        // } else {
        //   if (positionCustomScrollView >=
        //       positionCustomScrollViewSearchFalseFixed) {
        //     setState(() {
        //       isScrollableMenu = true;
        //     });
        //   } else {
        //     setState(() {
        //       isScrollableMenu = false;
        //     });
        //   }
        // }
      },
    );
    _scrollMenuItem.addListener(() {
      double positionMenuItemScrollView = _scrollMenuItem.position.pixels;
      double positionMenuItemScrollViewMin =
          _scrollMenuItem.position.minScrollExtent;
      if (positionMenuItemScrollView == positionMenuItemScrollViewMin &&
          _scrollController.position.pixels ==
              _scrollController.position.maxScrollExtent) {
        setState(() {
          isScrollableMenu = false;
        });
      }
    });

    super.initState();
  }

  @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;
    double widthScreen = responsiveWidthScreen(context);
    double maxWidthScreen = getMaxWidthScreen(context, useResponsive);
    List<CategoryList> categoryList = [];
    List<FavoriteGroup> favList = [];
    List<FilterMenu> categoryNonFav = [];
    List<FilterMenu> categoryFav = [];
    List<FilterMenu> categoryFavAfterSelect = [];
    List<FilterMenu> categoryMenuAfterSelect = [];
    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) {
                          for (var menu in categoryDefault) {
                            if (!menu.isFavMenu) {
                              categoryNonFav.add(menu);
                            } else {
                              categoryFav.add(menu);
                            }
                          }
                          allMenu = categoryNonFav;

                          var nn = {
                            "name": "All",
                            "id": "0",
                          }; // all dulu, biar ada bisa klik all
                          categoryList.add(CategoryList.createCategoryList(nn));
                          for (var nameCat in categoryNonFav) {
                            if (nameCat.type == typeCategory) {
                              var n = {
                                "id": nameCat.id,
                                "name": nameCat.categoryName
                              };
                              categoryList
                                  .add(CategoryList.createCategoryList(n));
                            }
                          }
                          for (var nameFav in categoryFav) {
                            if (nameFav.type == typeCategory) {
                              var nfav = {
                                "name": nameFav.categoryName,
                                "id": nameFav.id
                              };
                              favList.add(FavoriteGroup.add(nfav));
                            }
                          }
                          if (isFirstLoad) {
                            context
                                .read<FavSelectedBar>()
                                .selectedBarFav(0, favList[0].id);
                            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<MenuSelectedBar, List<dynamic>>(
                            builder:
                                (contextSelectedBarMenu, listDynamicBarMenu) {
                              if (categoryNonFav.isNotEmpty &&
                                  categoryList.isNotEmpty) {
                                List<FilterMenu> temprSelectedMenu = [];
                                for (var nameCat in categoryNonFav) {
                                  if (listDynamicBarMenu.length == 2 &&
                                      nameCat.categoryName ==
                                          listDynamicBarMenu[1]) {
                                    temprSelectedMenu.add(nameCat);
                                  }
                                }
                                if (listDynamicBarMenu.length == 2 &&
                                    listDynamicBarMenu[0] == 0) {
                                  categoryMenuAfterSelect = categoryNonFav;
                                } else {
                                  categoryMenuAfterSelect = temprSelectedMenu;
                                }
                                // if (listDynamicBarMenu.length == 2 &&
                                //     listDynamicBarMenu[1] != "0" &&
                                //     isScrollableMenu == true) {
                                //   _scrollMenuItem.animateTo(
                                //     10,
                                //     duration:
                                //         Duration(milliseconds: animatedTime),
                                //     curve: Curves.fastOutSlowIn,
                                //   );
                                // }
                              }
                              return Stack(
                                children: [
                                  Container(
                                    height: MediaQuery.of(context).size.height,
                                    margin: EdgeInsets.symmetric(
                                        horizontal: paddingLeftRight),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        customAppBar(context, paddingLeftRight,
                                            appBarHeight),
                                        SizedBox(
                                          height: (isSearchActive) ? 16 : 20,
                                        ),
                                        AnimatedSwitcher(
                                          duration: Duration(
                                              milliseconds: animatedTime),
                                          transitionBuilder: (Widget child,
                                              Animation<double> animation) {
                                            return ScaleTransition(
                                                scale: animation, child: child);
                                          },
                                          child: (isSearchActive)
                                              ? SizedBox(
                                                  height: searchFieldHeight,
                                                  child: TextField(
                                                    key: const Key(
                                                        'SearchField'),
                                                    style: TextStyle(
                                                      color: Colors.black,
                                                      fontFamily: fontFamily,
                                                      fontSize: 15,
                                                    ),
                                                    decoration: InputDecoration(
                                                      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),
                                                      ),
                                                    ),
                                                  ),
                                                )
                                              : const SizedBox(
                                                  key: Key('SearchField'),
                                                ),
                                        ),
                                        Expanded(
                                          child: CustomScrollView(
                                            controller: _scrollController,
                                            slivers: [
                                              SliverToBoxAdapter(
                                                child: SizedBox(
                                                  height: (isSearchActive)
                                                      ? spacerHeight
                                                      : 0,
                                                ),
                                              ),
                                              SliverToBoxAdapter(
                                                child: Container(
                                                  height: favListHeight,
                                                  child: FavoriteList(
                                                    favoriteList: favList,
                                                  ),
                                                ),
                                              ),
                                              const SliverToBoxAdapter(
                                                child: SizedBox(
                                                  height: 13.5,
                                                ),
                                              ),
                                              SliverToBoxAdapter(
                                                child: Container(
                                                  height: favItemHeight,
                                                  child: ListView.builder(
                                                      scrollDirection:
                                                          Axis.horizontal,
                                                      itemCount:
                                                          categoryFavAfterSelect
                                                              .length,
                                                      itemBuilder:
                                                          (context, i) {
                                                        double
                                                            paddingLeftRigthGrid =
                                                            9;
                                                        double widthGrid = 136;
                                                        return FavGridMenu(
                                                          categoryFavAfterSelect:
                                                              categoryFavAfterSelect,
                                                          widthGrid: widthGrid,
                                                          paddingLeftRigthGrid:
                                                              paddingLeftRigthGrid,
                                                          i: i,
                                                        );
                                                      }),
                                                ),
                                              ),
                                              SliverToBoxAdapter(
                                                child: SizedBox(
                                                  height: spacerAboveCat,
                                                ),
                                              ),
                                              SliverToBoxAdapter(
                                                child: defaultText(
                                                  context,
                                                  'Category',
                                                  style: categoryStyle(),
                                                ),
                                              ),
                                              SliverToBoxAdapter(
                                                child: SizedBox(
                                                  height: spacerAboveCatList,
                                                ),
                                              ),
                                              SliverPersistentHeader(
                                                pinned: true,
                                                delegate: Delegate(
                                                  catListHeight,
                                                  categoryList,
                                                ),
                                              ),
                                              SliverToBoxAdapter(
                                                child: SizedBox(
                                                  height: spacerAboveMenuItem,
                                                ),
                                              ),
                                              SliverToBoxAdapter(
                                                  child: Container(
                                                height: heightLeft,
                                                child: ListView.builder(
                                                  controller: (isScrollableMenu)
                                                      ? _scrollMenuItem
                                                      : null,
                                                  physics: (!isScrollableMenu)
                                                      ? const NeverScrollableScrollPhysics()
                                                      : null,
                                                  shrinkWrap: (isScrollableMenu)
                                                      ? true
                                                      : false,
                                                  itemCount:
                                                      categoryMenuAfterSelect
                                                          .length,
                                                  itemBuilder: (context, i) {
                                                    return MenuListUtama(
                                                      categoryNonFav:
                                                          categoryMenuAfterSelect,
                                                      i: i,
                                                    );
                                                  },
                                                ),
                                              )),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Positioned(
                                    bottom: 0,
                                    child: Container(
                                      width: MediaQuery.of(context).size.width,
                                      height: 61,
                                      decoration: BoxDecoration(
                                        color: buttonColor,
                                        borderRadius: const BorderRadius.only(
                                            topRight: Radius.circular(30)),
                                      ),
                                      child: Row(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.center,
                                        children: [
                                          Expanded(
                                            child: Container(
                                              margin: EdgeInsets.only(
                                                  left: paddingLeftRight),
                                              child: defaultText(
                                                  context, 'Rp 25,000'),
                                            ),
                                          ),
                                          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: addButtonBotoomCart(
                                                      color: buttonColor,
                                                    ),
                                                  ),
                                                  const SizedBox(
                                                    width: 7,
                                                  ),
                                                  // fontAwesome(
                                                  //   context,
                                                  //   shoppingCart,
                                                  //   1,
                                                  //   color: buttonColor,
                                                  // )
                                                ],
                                              ),
                                            ),
                                          ),
                                          const SizedBox(
                                            width: 23,
                                          )
                                        ],
                                      ),
                                    ),
                                  )
                                ],
                              );
                            },
                          );
                        });
                      },
                    )
                  : (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(),
            ),
          ),
        );
      },
    );
  }

  Container girdFavItem(
    List<FilterMenu> favListItem,
    int i,
    double widthGrid,
    double paddingLeftRigthGrid,
    BuildContext context,
  ) {
    bool addCondition = true;
    return Container(
      margin: EdgeInsets.only(
        left: (i == 0) ? 0 : 8, // paling awal gausah dikasih margin
        right: (i == favListItem.length - 1)
            ? 0
            : 8, // paling akhir gausah dikasi margin
      ),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(5),
        color: gridCardBackgroundColor,
      ),
      height: double.infinity,
      width: widthGrid,
      child: Container(
        margin: EdgeInsets.only(
          top: 8,
          left: paddingLeftRigthGrid,
          right: paddingLeftRigthGrid,
          bottom: 16,
        ),
        // color: Colors.red,
        child: Column(
          children: [
            Container(
              width: widthGrid - (2 * paddingLeftRigthGrid),
              height: widthGrid - (2 * paddingLeftRigthGrid),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                // color: Colors.red,
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Image(
                  fit: BoxFit.fill,
                  image: NetworkImage(favListItem[i].imageUrlMedium),
                ),
              ),
            ),
            const SizedBox(
              height: 3,
            ),
            Container(
              width: widthGrid - (2 * paddingLeftRigthGrid),
              height: 28,
              // color: Colors.blue,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Expanded(
                    child: defaultText(
                      context,
                      favListItem[i].name,
                      maxLines: 2,
                      overFlow: TextOverflow.ellipsis,
                      style: menuNameGridFav(),
                    ),
                  ),
                  Container(
                    width: 40,
                    child: defaultText(
                      context,
                      'Rp ${formatNumber().format(amountParseToInt(favListItem[i].price))}',
                      maxLines: 3,
                      overFlow: TextOverflow.ellipsis,
                      style: menuPriceGridFav(),
                    ),
                  )
                ],
              ),
            ),
            const SizedBox(
              height: 16,
            ),
            (addCondition)
                ? Container(
                    height: 30,
                    width: widthGrid - (2 * paddingLeftRigthGrid),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(6),
                      color: buttonColor,
                    ),
                    child: Center(
                      child: defaultText(
                        context,
                        'Tambah',
                        style: addButtonGridFav(),
                      ),
                    ),
                  )
                : Container(
                    height: 30,
                    width: widthGrid - (2 * paddingLeftRigthGrid),
                    child: Row(
                      children: [
                        Container(
                          width: 27,
                          height: 24,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(6),
                            color: buttonColor,
                          ),
                          child: const Center(
                            child: Image(
                              width: 13.33,
                              height: 13.33,
                              color: textInButton,
                              image: AssetImage('assets/icons/note.png'),
                            ),
                          ),
                        ),
                        const SizedBox(
                          width: 5,
                        ),
                        Container(
                          width: 22,
                          height: 22,
                          child: const Image(
                            image: AssetImage('assets/icons/minus.png'),
                          ),
                        ),
                        Expanded(
                          child: Center(
                            child: defaultText(
                              context,
                              '10',
                              style: amountGridFav(),
                            ),
                          ),
                        ),
                        Container(
                          width: 22,
                          height: 22,
                          child: const Image(
                            image: AssetImage('assets/icons/plus.png'),
                          ),
                        )
                      ],
                    ),
                  )
          ],
        ),
      ),
    );
  }

  Container customAppBar(
      BuildContext context, double paddingLeftRight, double appBarHeight) {
    return Container(
        // color: Colors.red,
        margin: EdgeInsets.symmetric(horizontal: paddingLeftRight),
        height: appBarHeight,
        child: Row(
          children: [
            defaultText(
              context,
              'Meja 12',
              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,
            ),
            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 List<CategoryList> categoryList;
  Delegate(this.catListHeight, this.categoryList);
  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      height: catListHeight,
      child: CategoryListHome(
        categoryList: categoryList,
      ),
    );
  }

  @override
  double get maxExtent => catListHeight;

  @override
  double get minExtent => catListHeight;

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