// ignore_for_file: sized_box_for_whitespace

import 'package:byod/bloc/order_bloc.dart';
import 'package:byod/helper/widget/poni_bottom_sheet.dart';
import 'package:byod/models/orders.dart';
import 'package:byod/ui/home/variant_cat.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../bloc/order_variant_temporary.dart';
import '../../helper/helper.dart';
import '../../helper/widget/note_modal_bottom_sheet.dart';
import '../../helper/widget/style.dart';
import '../../models/filter_menu.dart';
import '../../models/order_details.dart';
import '../../models/order_variants.dart';
import 'bottom_sheet_menu.dart';
import 'bottom_sheet_variant.dart';

class MenuListUtama extends StatelessWidget {
  const MenuListUtama({
    Key? key,
    required this.categoryNonFav,
    required this.i,
    required this.widthScreen,
    required this.scrollController,
  }) : super(key: key);

  final List<FilterMenu> categoryNonFav;
  final int i;
  final double widthScreen;
  final ScrollController scrollController;

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        (categoryNonFav[i].type == typeCategory)
            ? defaultText(
                context,
                categoryNonFav[i].categoryName,
                maxLines: 1,
                overFlow: TextOverflow.ellipsis,
                style: categoryNameStyle(),
              )
            : const SizedBox(),
        (categoryNonFav[i].type == typeCategory)
            ? const Divider(
                thickness: 0.5,
                color: textColorBlack,
              )
            : const SizedBox(),
        (categoryNonFav[i].type == typeGroup)
            ? Container(
                margin: const EdgeInsets.only(
                  top: 6,
                ),
                child: defaultText(
                  context,
                  maxLines: 3,
                  overFlow: TextOverflow.ellipsis,
                  categoryNonFav[i].groupName,
                  style: subCategoryStyle(),
                ),
              )
            : const SizedBox(),
        (categoryNonFav[i].type == typeMenu)
            ? Container(
                margin: EdgeInsets.only(
                  top: 19,
                  bottom: (i + 1 == categoryNonFav.length) ? 85 : 19,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Container(
                      height: 125,
                      width: double.infinity,
                      child: Row(
                        children: [
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                defaultText(
                                  context,
                                  categoryNonFav[i].name,
                                  style: menuNameStyle(),
                                ),
                                const Spacer(),
                                defaultText(
                                  maxLines: 2,
                                  overFlow: TextOverflow.ellipsis,
                                  context,
                                  categoryNonFav[i].description,
                                  style: deskripsiMenuStyle(),
                                ),
                                const SizedBox(
                                  height: 4,
                                ),
                                defaultText(
                                  maxLines: 1,
                                  overFlow: TextOverflow.ellipsis,
                                  context,
                                  'Rp ${formatNumber().format(amountParseToInt(categoryNonFav[i].price))}',
                                  style: amountMenuStyle(),
                                )
                              ],
                            ),
                          ),
                          Container(
                            width: 12,
                            height: double.infinity,
                          ),
                          GestureDetector(
                            onTap: () {
                              FocusScopeNode currentFocus =
                                  FocusScope.of(context);

                              if (!currentFocus.hasPrimaryFocus) {
                                currentFocus.unfocus();
                              }
                              showModalBottomSheet(
                                backgroundColor: Colors.white,
                                isScrollControlled: true,
                                context: context,
                                builder: (context) {
                                  return ShowMenuModal(
                                    imageUrl: categoryNonFav[i].imageUrlMedium,
                                    namaMenu: categoryNonFav[i].name,
                                    hargaMenu: amountParseToInt(
                                        categoryNonFav[i].price),
                                    isHavevariant:
                                        categoryNonFav[i].variantCat.isNotEmpty
                                            ? true
                                            : false,
                                    description: categoryNonFav[i].description,
                                    id: categoryNonFav[i].id,
                                    variantCat: categoryNonFav[i].variantCat,
                                    isSell: categoryNonFav[i].isSell,
                                  );
                                },
                              );
                            },
                            child: Container(
                              width: 125,
                              height: 125,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(14),
                                color: disabledColor.withOpacity(0.8),
                              ),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(14),
                                child: (categoryNonFav[i].imageUrlMedium != '')
                                    ? Image(
                                        fit: BoxFit.fill,
                                        image: NetworkImage(
                                          categoryNonFav[i].imageUrlMedium,
                                        ),
                                      )
                                    : const Image(
                                        fit: BoxFit.fill,
                                        image: AssetImage('assets/noimage.png'),
                                      ),
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                    Container(
                      height: 8,
                      width: double.infinity,
                    ),
                    addRemoveQuantity(context, categoryNonFav[i])
                  ],
                ),
              )
            : const SizedBox(),
      ],
    );
  }

  BlocBuilder addRemoveQuantity(BuildContext context, FilterMenu menuUtama) {
    List<OrderVariant> orderVariants = [];
    return BlocBuilder<OrdersBloc, List<Orders>>(
      builder: (contextOrders, list) {
        bool
            addCondition; // true untuk menampilkan tambah, false untuk menampilkan quantity plus minus
        int indexListOrderan =
            list.indexWhere((listOrderan) => listOrderan.id == menuUtama.id);
        int initialValue;
        if (indexListOrderan != -1) {
          if (menuUtama.variantCat.isNotEmpty) {
            addCondition = true; // kalau menu itu ada variantnya, biarin true
          } else {
            addCondition = false;
          }

          initialValue = list[indexListOrderan].totalItem;
        } else {
          addCondition = true;
          initialValue = 0;
        }
        String variantButtonCount = '';
        if (initialValue == 1 && menuUtama.variantCat.isNotEmpty) {
          variantButtonCount = '$initialValue Item';
        } else if (initialValue > 1 && menuUtama.variantCat.isNotEmpty) {
          variantButtonCount = '$initialValue Items';
        }
        final noteController = TextEditingController(
            text: (indexListOrderan != -1) ? list[indexListOrderan].note : '');
        return AnimatedSwitcher(
          duration: Duration(milliseconds: animatedTime),
          transitionBuilder: (Widget child, Animation<double> animation) {
            return ScaleTransition(scale: animation, child: child);
          },
          child: (addCondition)
              ? Container(
                  key: const Key('AddButtonMenuKey'),
                  height: 36,
                  width: double.infinity,
                  child: Row(
                    children: [
                      const Spacer(),
                      GestureDetector(
                        onTap: () {
                          FocusScopeNode currentFocus = FocusScope.of(context);

                          if (!currentFocus.hasPrimaryFocus) {
                            currentFocus.unfocus();
                          }

                          if (menuUtama.isSell) {
                            if (menuUtama.variantCat.isNotEmpty) {
                              if (indexListOrderan == -1) {
                                context
                                    .read<OrderVariantTemporaryBloc>()
                                    .insertDataVariant(
                                  menuUtama.id,
                                  amountParseToInt(menuUtama.price),
                                  1,
                                  [],
                                ); // check pada bloc untuk mengethui list arraynya
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (_) => VariantCat(
                                              namaMenu: menuUtama.name,
                                              variantCategories:
                                                  menuUtama.variantCat,
                                              initPrice: amountParseToInt(
                                                  menuUtama.price),
                                              idItem: menuUtama.id,
                                              imageUrl:
                                                  menuUtama.imageUrlThumbnail,
                                              listCurrentOrder: list,
                                              orderDetail: OrderDetail(
                                                allIdVariant: '',
                                                totalItem: 0,
                                                totalHarga: 0,
                                                note: '',
                                                orderVariant: [],
                                              ),
                                            )));
                              } else {
                                showModalBottomSheet(
                                  backgroundColor: Colors.white.withOpacity(0),
                                  isScrollControlled: true,
                                  context: context,
                                  builder: (context) {
                                    return CustomizeVariant(
                                        orders: list[indexListOrderan],
                                        variantCat: menuUtama.variantCat);
                                  },
                                );
                              }
                            } else {
                              if (initialValue == 0) {
                                initialValue += 1;
                                context.read<OrdersBloc>().insertData([
                                  [
                                    menuUtama.id,
                                    menuUtama.name,
                                    initialValue,
                                    amountParseToInt(menuUtama.price),
                                    list,
                                    menuUtama.imageUrlMedium,
                                    orderVariants,
                                    amountParseToInt(menuUtama.price),
                                    (indexListOrderan != -1)
                                        ? list[indexListOrderan].note
                                        : ''
                                  ]
                                ], context);
                                // setState(() {});
                              }
                            }
                          }
                        },
                        child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            color: buttonColor,
                          ),
                          height: double.infinity,
                          width: 125,
                          child: Center(
                            child: defaultText(
                              context,
                              (menuUtama.isSell == false)
                                  ? 'Habis'
                                  : (initialValue == 0)
                                      ? 'Tambah'
                                      : (initialValue > 0 &&
                                              menuUtama.variantCat.isNotEmpty)
                                          ? variantButtonCount
                                          : 'Tambah',
                              style: addButtonMenu(),
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                )
              : Container(
                  key: const Key('AddButtonMenuKey'),
                  height: 36,
                  width: 125,
                  child: Row(
                    children: [
                      GestureDetector(
                        onTap: () {
                          FocusScopeNode currentFocus = FocusScope.of(context);

                          if (!currentFocus.hasPrimaryFocus) {
                            currentFocus.unfocus();
                          }
                          showModalBottomSheet(
                            backgroundColor: backgroundColor,
                            isScrollControlled: true,
                            context: context,
                            builder: (context) {
                              return NoteModalBottomSheet(
                                noteController: noteController,
                                initialValue: initialValue,
                                orderVariants: orderVariants,
                                menuItem: menuUtama,
                                lisrOrders: list,
                              );
                            },
                          );
                        },
                        child: 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,
                      ),
                      Expanded(
                        child: Container(
                          height: 22,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(30),
                            color: Colors.white,
                          ),
                          child: Stack(
                            children: [
                              Positioned(
                                left: 0,
                                child: GestureDetector(
                                  onTap: () {
                                    FocusScopeNode currentFocus =
                                        FocusScope.of(context);

                                    if (!currentFocus.hasPrimaryFocus) {
                                      currentFocus.unfocus();
                                    }
                                    if (initialValue > 0) {
                                      initialValue -= 1;
                                      context.read<OrdersBloc>().insertData([
                                        [
                                          menuUtama.id,
                                          menuUtama.name,
                                          initialValue,
                                          amountParseToInt(menuUtama.price),
                                          list,
                                          menuUtama.imageUrlMedium,
                                          orderVariants,
                                          amountParseToInt(menuUtama.price),
                                          (indexListOrderan != -1)
                                              ? list[indexListOrderan].note
                                              : ''
                                        ]
                                      ], context);
                                      // setState(() {});
                                    }
                                  },
                                  child: Container(
                                    width: 22,
                                    height: 22,
                                    child: Image(
                                      color: buttonColor,
                                      image: const AssetImage(
                                          'assets/icons/minus.png'),
                                    ),
                                  ),
                                ),
                              ),
                              Positioned(
                                right: 0,
                                child: GestureDetector(
                                  onTap: () {
                                    FocusScopeNode currentFocus =
                                        FocusScope.of(context);

                                    if (!currentFocus.hasPrimaryFocus) {
                                      currentFocus.unfocus();
                                    }
                                    initialValue += 1;
                                    context.read<OrdersBloc>().insertData([
                                      [
                                        menuUtama.id,
                                        menuUtama.name,
                                        initialValue,
                                        amountParseToInt(menuUtama.price),
                                        list,
                                        menuUtama.imageUrlMedium,
                                        orderVariants,
                                        amountParseToInt(menuUtama.price),
                                        (indexListOrderan != -1)
                                            ? list[indexListOrderan].note
                                            : '',
                                      ]
                                    ], context);
                                  },
                                  child: Container(
                                    width: 22,
                                    height: 22,
                                    child: const Image(
                                      image:
                                          AssetImage('assets/icons/plus.png'),
                                    ),
                                  ),
                                ),
                              ),
                              Center(
                                child: Container(
                                  height: 22,
                                  child: Center(
                                    child: defaultText(
                                      context,
                                      initialValue.toString(),
                                      style: amountGridFav(),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
        );
      },
    );
  }
}
