// ignore_for_file: sized_box_for_whitespace

import 'package:byod/bloc/order_bloc.dart';
import 'package:byod/helper/widget/button_modal.dart';
import 'package:byod/helper/widget/plus_minus_button.dart';
import 'package:byod/models/orders.dart';
import 'package:byod/ui/screen_responsive.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_variants.dart';
import 'bottom_sheet_menu_new.dart';
import 'bottom_sheet_variant.dart';
import 'variant_cat_new.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        (categoryNonFav[i].type == typeGroup &&
                categoryNonFav[i].categoryId == idCategory)
            ? 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 &&
                categoryNonFav[i].categoryId == idCategory)
            ? 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,
                                  // );
                                  double widthImage =
                                      widthScreen - 2 * paddingLeftRight;
                                  return ScreenResponsive(
                                    widget: ShowMenuBottomSheet(
                                      menuDetail: categoryNonFav,
                                      i: i,
                                      widthScreen: widthScreen,
                                      widthImage: widthImage,
                                    ),
                                    isCoreLayout: true,
                                    widthScreen:
                                        MediaQuery.of(context).size.width,
                                  );
                                },
                              );
                            },
                            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 = 0;
        if (indexListOrderan != -1) {
          if (menuUtama.variantCat.isNotEmpty) {
            addCondition = true; // kalau menu itu ada variantnya, biarin true
          } else {
            addCondition = false;
          }

          if (list[indexListOrderan].orderDetail.isNotEmpty) {
            for (int d = 0;
                d < list[indexListOrderan].orderDetail.length;
                d++) {
              initialValue += list[indexListOrderan].orderDetail[d].totalItem;
            }
          } else {
            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 : '');

        void minus() {
          FocusScopeNode currentFocus = FocusScope.of(context);

          if (!currentFocus.hasPrimaryFocus) {
            currentFocus.unfocus();
          }
          if (initialValue > 0) {
            initialValue -= 1;
            Map<String, dynamic> insertData = {
              'menu_id': menuUtama.id,
              'menu_name': menuUtama.name,
              'initvalue': initialValue,
              'menu_price': amountParseToInt(menuUtama.price),
              'total_price': amountParseToInt(menuUtama.price),
              'old_order': list,
              'image_url': menuUtama.imageUrlMedium,
              'order_variant': [],
              'note':
                  (indexListOrderan != -1) ? list[indexListOrderan].note : '',
            };
            context.read<OrdersBloc>().insertData(insertData);
            // setState(() {});
          }
        }

        void plus() {
          FocusScopeNode currentFocus = FocusScope.of(context);

          if (!currentFocus.hasPrimaryFocus) {
            currentFocus.unfocus();
          }
          initialValue += 1;
          Map<String, dynamic> insertData = {
            'menu_id': menuUtama.id,
            'menu_name': menuUtama.name,
            'initvalue': initialValue,
            'menu_price': amountParseToInt(menuUtama.price),
            'total_price': amountParseToInt(menuUtama.price),
            'old_order': list,
            'image_url': menuUtama.imageUrlMedium,
            'order_variant': [],
            'note': (indexListOrderan != -1) ? list[indexListOrderan].note : '',
          };
          context.read<OrdersBloc>().insertData(insertData);
        }

        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: [],
                                //       ),
                                //     ),
                                //   ),
                                // );
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (_) => VariantCatNew(
                                      initPrice:
                                          amountParseToInt(menuUtama.price),
                                      variantCategories: menuUtama.variantCat,
                                      namaMenu: menuUtama.name,
                                      idItem: menuUtama.id,
                                      imageUrl: menuUtama.imageUrlMedium,
                                      listCurrentOrder: list,
                                    ),
                                  ),
                                );
                              } 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;
                                Map<String, dynamic> insertData = {
                                  'menu_id': menuUtama.id,
                                  'menu_name': menuUtama.name,
                                  'initvalue': initialValue,
                                  'menu_price':
                                      amountParseToInt(menuUtama.price),
                                  'total_price':
                                      amountParseToInt(menuUtama.price),
                                  'old_order': list,
                                  'image_url': menuUtama.imageUrlMedium,
                                  'order_variant': [],
                                  'note': (indexListOrderan != -1)
                                      ? list[indexListOrderan].note
                                      : '',
                                };
                                context
                                    .read<OrdersBloc>()
                                    .insertData(insertData);
                                // 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: addButton(),
                        //     ),
                        //   ),
                        // ),
                        child: ButtonComponent(
                          buttonColor: buttonColor,
                          teksButton: (menuUtama.isSell == false)
                              ? 'Habis'
                              : (initialValue == 0)
                                  ? 'Tambah'
                                  : (initialValue > 0 &&
                                          menuUtama.variantCat.isNotEmpty)
                                      ? variantButtonCount
                                      : 'Tambah',
                          fontTeksSize: 12,
                          height: 36,
                          width: 125,
                        ),
                      )
                    ],
                  ),
                )
              : 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,
                                from: fromMenu,
                                contextFrom: context,
                              );
                            },
                          );
                        },
                        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: PlusMinusButton(
                          initialValue: initialValue,
                          plus: plus,
                          minus: minus,
                          backgroundAmountColor: backgroundWhite,
                        ),
                        // 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-blue.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(),
                        //           ),
                        //         ),
                        //       ),
                        //     ),
                        //   ],
                        // ),
                      ),
                    ],
                  ),
                ),
        );
      },
    );
  }
}
