// ignore_for_file: sized_box_for_whitespace, avoid_unnecessary_containers

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:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../bloc/order_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 '../screen_responsive.dart';
import 'bottom_sheet_menu_new.dart';
import 'bottom_sheet_variant.dart';
import 'variant_cat.dart';

class FavGridMenu extends StatelessWidget {
  const FavGridMenu({
    Key? key,
    required this.categoryFavAfterSelect,
    required this.widthGrid,
    required this.paddingLeftRigthGrid,
    required this.i,
  }) : super(key: key);

  final List<FilterMenu> categoryFavAfterSelect;
  final double widthGrid;
  final double paddingLeftRigthGrid;
  final int i;

  @override
  Widget build(BuildContext context) {
    double widthScreen = responsiveWidthScreen(context);
    return Container(
      margin: EdgeInsets.only(
        left: (i == 0) ? 0 : 8, // paling awal gausah dikasih margin
        right: (i == categoryFavAfterSelect.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: disabledColor.withOpacity(0.8),
              ),
              child: 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: categoryFavAfterSelect[i].imageUrlMedium,
                      //   namaMenu: categoryFavAfterSelect[i].name,
                      //   hargaMenu:
                      //       amountParseToInt(categoryFavAfterSelect[i].price),
                      //   isHavevariant:
                      //       categoryFavAfterSelect[i].variantCat.isNotEmpty
                      //           ? true
                      //           : false,
                      //   description: categoryFavAfterSelect[i].description,
                      //   id: categoryFavAfterSelect[i].id,
                      //   variantCat: categoryFavAfterSelect[i].variantCat,
                      //   isSell: categoryFavAfterSelect[i].isSell,
                      // );
                      double widthImage = widthScreen - 2 * paddingLeftRight;
                      return ScreenResponsive(
                        widget: ShowMenuBottomSheet(
                          menuDetail: categoryFavAfterSelect,
                          i: i,
                          widthScreen: widthScreen,
                          widthImage: widthImage,
                        ),
                        isCoreLayout: true,
                        widthScreen: MediaQuery.of(context).size.width,
                      );
                    },
                  );
                },
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: (categoryFavAfterSelect[i].imageUrlMedium != '')
                      ? Image(
                          fit: BoxFit.fill,
                          image: NetworkImage(
                              categoryFavAfterSelect[i].imageUrlMedium),
                        )
                      : const Image(
                          fit: BoxFit.fill,
                          image: AssetImage('assets/noimage.png')),
                ),
              ),
            ),
            const SizedBox(
              height: 3,
            ),
            Container(
              width: widthGrid - (2 * paddingLeftRigthGrid),
              height: 28,
              // color: Colors.blue,
              child: defaultText(
                context,
                categoryFavAfterSelect[i].name,
                maxLines: 2,
                overFlow: TextOverflow.ellipsis,
                style: menuNameGridFav(),
              ),
              // child: Row(
              //   crossAxisAlignment: CrossAxisAlignment.end,
              //   children: [
              //     Expanded(
              //       child: defaultText(
              //         context,
              //         categoryFavAfterSelect[i].name,
              //         maxLines: 2,
              //         overFlow: TextOverflow.ellipsis,
              //         style: menuNameGridFav(),
              //       ),
              //     ),
              //     Container(
              //       width: 40,
              //       child: defaultText(
              //         context,
              //         'Rp ${formatNumber().format(amountParseToInt(categoryFavAfterSelect[i].price))}',
              //         maxLines: 3,
              //         overFlow: TextOverflow.ellipsis,
              //         style: menuPriceGridFav(),
              //       ),
              //     )
              //   ],
              // ),
            ),
            const SizedBox(
              height: 4,
            ),
            Container(
              width: widthGrid - (2 * paddingLeftRigthGrid),
              height: 20,
              child: Align(
                alignment: Alignment.centerRight,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    (amountParseToInt(categoryFavAfterSelect[i].price) <
                            amountParseToInt(
                                categoryFavAfterSelect[i].originalPrice))
                        ? defaultText(
                            context,
                            'Rp ${formatNumber().format(amountParseToInt(categoryFavAfterSelect[i].price))}',
                            maxLines: 3,
                            overFlow: TextOverflow.ellipsis,
                            style: menuPriceGridFav(
                              font: 7,
                              decoration: TextDecoration.lineThrough,
                            ),
                          )
                        : const SizedBox(),
                    (amountParseToInt(categoryFavAfterSelect[i].price) <
                            amountParseToInt(
                                categoryFavAfterSelect[i].originalPrice))
                        ? const SizedBox(
                            width: 5,
                          )
                        : const SizedBox(),
                    defaultText(
                      context,
                      'Rp ${formatNumber().format(amountParseToInt(categoryFavAfterSelect[i].originalPrice))}',
                      maxLines: 3,
                      overFlow: TextOverflow.ellipsis,
                      style: menuPriceGridFav(),
                    ),
                  ],
                ),
              ),
            ),
            addRemoveQuantity(context, categoryFavAfterSelect[i])
          ],
        ),
      ),
    );
  }

  BlocBuilder addRemoveQuantity(BuildContext context, FilterMenu menuFav) {
    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 == menuFav.id);
        int initialValue;
        if (indexListOrderan != -1) {
          if (menuFav.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 && menuFav.variantCat.isNotEmpty) {
          variantButtonCount = '$initialValue Item';
        } else if (initialValue > 1 && menuFav.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;
            context.read<OrdersBloc>().insertData([
              [
                menuFav.id,
                menuFav.name,
                initialValue,
                amountParseToInt(menuFav.price),
                list,
                menuFav.imageUrlMedium,
                orderVariants,
                amountParseToInt(menuFav.price),
                (indexListOrderan != -1) ? list[indexListOrderan].note : ''
              ]
            ]);
            // setState(() {});
          }
        }

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

          if (!currentFocus.hasPrimaryFocus) {
            currentFocus.unfocus();
          }
          initialValue += 1;
          context.read<OrdersBloc>().insertData([
            [
              menuFav.id,
              menuFav.name,
              initialValue,
              amountParseToInt(menuFav.price),
              list,
              menuFav.imageUrlMedium,
              orderVariants,
              amountParseToInt(menuFav.price),
              (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)
              ? GestureDetector(
                  key: const Key('AddButton'),
                  onTap: () {
                    FocusScopeNode currentFocus = FocusScope.of(context);

                    if (!currentFocus.hasPrimaryFocus) {
                      currentFocus.unfocus();
                    }
                    if (menuFav.isSell) {
                      if (menuFav.variantCat.isNotEmpty) {
                        if (indexListOrderan == -1) {
                          context
                              .read<OrderVariantTemporaryBloc>()
                              .insertDataVariant(
                            menuFav.id,
                            amountParseToInt(menuFav.price),
                            1,
                            [],
                          ); // check pada bloc untuk mengethui list arraynya
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (_) => VariantCat(
                                        namaMenu: menuFav.name,
                                        variantCategories: menuFav.variantCat,
                                        initPrice:
                                            amountParseToInt(menuFav.price),
                                        idItem: menuFav.id,
                                        imageUrl: menuFav.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: menuFav.variantCat,
                              );
                            },
                          );
                        }
                      } else {
                        if (initialValue == 0) {
                          initialValue += 1;
                          context.read<OrdersBloc>().insertData([
                            [
                              menuFav.id,
                              menuFav.name,
                              initialValue,
                              amountParseToInt(menuFav.price),
                              list,
                              menuFav.imageUrlMedium,
                              orderVariants,
                              amountParseToInt(menuFav.price),
                              (indexListOrderan != -1)
                                  ? list[indexListOrderan].note
                                  : ''
                            ]
                          ]);
                          // setState(() {});
                        }
                      }
                    }
                  },
                  // child: Container(
                  //   height: 30,
                  //   width: widthGrid - (2 * paddingLeftRigthGrid),
                  //   decoration: BoxDecoration(
                  //     borderRadius: BorderRadius.circular(6),
                  //     color: (menuFav.isSell) ? buttonColor : Colors.grey,
                  //   ),
                  //   child: Center(
                  //     child: defaultText(
                  //       context,
                  //       (menuFav.isSell == false)
                  //           ? 'Habis'
                  //           : (initialValue == 0)
                  //               ? 'Tambah'
                  //               : (initialValue > 0 &&
                  //                       menuFav.variantCat.isNotEmpty)
                  //                   ? variantButtonCount
                  //                   : 'Tambah',
                  //       style: addButtonGridFav(),
                  //     ),
                  //   ),
                  // ),
                  child: ButtonComponent(
                    buttonColor: buttonColor,
                    teksButton: (menuFav.isSell == false)
                        ? 'Habis'
                        : (initialValue == 0)
                            ? 'Tambah'
                            : (initialValue > 0 &&
                                    menuFav.variantCat.isNotEmpty)
                                ? variantButtonCount
                                : 'Tambah',
                    height: 30,
                    fontTeksSize: 12,
                  ),
                )
              : Container(
                  key: const Key('AddButton'),
                  height: 30,
                  width: widthGrid - (2 * paddingLeftRigthGrid),
                  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: menuFav,
                                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,
                      ),
                      PlusMinusButton(
                        initialValue: initialValue,
                        minus: minus,
                        plus: plus,
                        backgroundAmountColor: backgroundWhite,
                        widthInitialValue: 86,
                      )
                      // GestureDetector(
                      //   onTap: () {
                      //     FocusScopeNode currentFocus = FocusScope.of(context);

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

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