// ignore_for_file: sized_box_for_whitespace

import 'package:byod/helper/helper.dart';
import 'package:byod/helper/widget/style.dart';
import 'package:flutter/material.dart';

import 'cat_list.dart';
import 'fav_list.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;
  final searchController = TextEditingController();
  final _scrollController = ScrollController();
  final _scrollMenuItem = ScrollController();

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

  @override
  void initState() {
    _scrollController.addListener(
      () {
        // if (_scrollController.position.pixels >=
        //     (_scrollController.position.maxScrollExtent - 100)) {}
        double positionCustomScrollView = _scrollController.position.pixels;
        if (isSearchActive) {
          if (positionCustomScrollView == positionCustomScrollViewFixed) {
            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;

      if (positionMenuItemScrollView == 0) {
        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;
    return SafeArea(
      child: Scaffold(
        backgroundColor: backgroundColor,
        body: 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: const FavoriteList(),
                      ),
                    ),
                    const SliverToBoxAdapter(
                      child: SizedBox(
                        height: 13.5,
                      ),
                    ),
                    SliverToBoxAdapter(
                      child: Container(
                        height: favItemHeight,
                        child: ListView.builder(
                            scrollDirection: Axis.horizontal,
                            itemCount: 5,
                            itemBuilder: (context, i) {
                              double paddingLeftRigthGrid = 9;
                              double widthGrid = 136;
                              return girdFavItem(
                                i,
                                widthGrid,
                                paddingLeftRigthGrid,
                                context,
                              );
                            }),
                      ),
                    ),
                    SliverToBoxAdapter(
                      child: SizedBox(
                        height: spacerAboveCat,
                      ),
                    ),
                    SliverToBoxAdapter(
                      child: defaultText(
                        context,
                        'Category',
                        style: categoryStyle(),
                      ),
                    ),
                    SliverToBoxAdapter(
                      child: SizedBox(
                        height: spacerAboveCatList,
                      ),
                    ),
                    SliverPersistentHeader(
                      pinned: true,
                      delegate: Delegate(catListHeight),
                    ),
                    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: 100,
                        itemBuilder: (context, i) {
                          return defaultText(context, 'Teks ke $i');
                        },
                      ),
                    )),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Container girdFavItem(int i, double widthGrid, double paddingLeftRigthGrid,
      BuildContext context) {
    bool addCondition = true;
    return Container(
      margin: EdgeInsets.only(
        left: (i == 0) ? 0 : 8,
        right: (i == 5 - 1) ? 0 : 8,
      ),
      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,
              ),
            ),
            const SizedBox(
              height: 3,
            ),
            Container(
              width: widthGrid - (2 * paddingLeftRigthGrid),
              height: 28,
              // color: Colors.blue,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Expanded(
                    child: defaultText(
                      context,
                      'BBQ Chicken Nachos',
                      maxLines: 2,
                      overFlow: TextOverflow.ellipsis,
                      style: menuNameGridFav(),
                    ),
                  ),
                  Container(
                    width: 40,
                    child: defaultText(
                      context,
                      'Rp 25,000',
                      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,
            ),
          ],
        ));
  }

  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;
  Delegate(this.catListHeight);
  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      height: catListHeight,
      child: const CategoryList(),
    );
  }

  @override
  double get maxExtent => catListHeight;

  @override
  double get minExtent => catListHeight;

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