// ignore_for_file: sized_box_for_whitespace, avoid_unnecessary_containers, must_be_immutable

import 'package:byod/bloc/order_variant_temporary.dart';
import 'package:byod/helper/helper.dart';
import 'package:byod/models/order_details.dart';
import 'package:byod/models/order_variants.dart';
import 'package:byod/models/variant_categories.dart';
import 'package:byod/ui/home/variant_cat.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../bloc/order_bloc.dart';
import '../../helper/widget/style.dart';
import '../../models/orders.dart';
import 'bottom_sheet_menu.dart';
import 'bottom_sheet_note.dart';
import 'bottom_sheet_variant.dart';

class MenuView extends StatefulWidget {
  bool isHaveItem;
  String id;
  int hargaFix;
  int hargaCoret;
  String namaMenu;
  String description;
  int itemCount;
  int itemKe;
  String imageUrl;
  String imageMedium;
  bool isHaveVariant;
  List<VariantCategories> variantCat;
  bool isSell;
  double widthScreenParent;
  bool isShimmer;
  MenuView({
    Key? key,
    required this.isHaveItem,
    required this.id,
    required this.hargaFix,
    required this.hargaCoret,
    required this.namaMenu,
    required this.description,
    required this.itemCount,
    required this.itemKe,
    required this.imageUrl,
    required this.imageMedium,
    required this.isHaveVariant,
    required this.isSell,
    this.variantCat = const [],
    required this.widthScreenParent,
    this.isShimmer = false,
  }) : super(key: key);

  @override
  State<MenuView> createState() => _MenuViewState();
}

class _MenuViewState extends State<MenuView> {
  // final ScrollController _scrollController = ScrollController();

  // int initialValue = 0;
  List<OrderVariant> orderVariants = [];

  @override
  Widget build(BuildContext context) {
    double widthScreen = responsiveWidthScreen(context);

    return Container(
      // height: MediaQuery.of(context).size.height * 0.18,
      margin: (widget.itemCount == widget.itemKe && widget.isHaveItem == true)
          ? EdgeInsets.only(bottom: MediaQuery.of(context).size.height * 0.085)
          : EdgeInsets.only(bottom: MediaQuery.of(context).size.height * 0.01),
      // decoration: BoxDecoration(
      //   borderRadius: BorderRadius.circular(roundedButton),
      //   // color: Colors.red
      // ),
      // color: Colors.red,
      child: Column(
        children: [
          GestureDetector(
            onTap: () {
              modalShowMenu(context, widget.isSell);
            },
            child: Container(
              // height: MediaQuery.of(context).size.height * 0.12,
              color: backgroundColor,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // nama menu dan harga
                  Container(
                    width: widthScreen * 0.6,
                    // margin: EdgeInsets.only(
                    //     top: MediaQuery.of(context).size.height * 0.01),
                    // color: Colors.red,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        textMenuList(
                          context,
                          widget.namaMenu,
                        ),
                        SizedBox(
                            height: MediaQuery.of(context).size.height * 0.01),
                        (widget.description != '')
                            ? textMenuDescription(
                                context,
                                widget.description,
                              )
                            : const SizedBox(),
                        (widget.description != '')
                            ? SizedBox(
                                height:
                                    MediaQuery.of(context).size.height * 0.01)
                            : const SizedBox(),
                        Row(
                          children: [
                            textAmountMenu(context, widget.hargaFix),
                            SizedBox(
                                width:
                                    MediaQuery.of(context).size.height * 0.005),
                            (widget.hargaFix < widget.hargaCoret)
                                ? textAmountCoret(context, widget.hargaCoret)
                                : const SizedBox(),
                          ],
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    width: widthScreen * 0.05,
                  ),
                  // gambar menu
                  Align(
                    alignment: Alignment.topCenter,
                    child: Container(
                      width: widthScreen * 0.25,
                      height: widthScreen * 0.25,
                      // height: double.infinity,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(roundedImage),
                        color: disabledColor.withOpacity(0.8),
                      ),
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(roundedImage),
                        child: (widget.imageUrl != '')
                            ? Image(
                                fit: BoxFit.fill,
                                image: NetworkImage(widget.imageUrl),
                              )
                            : const Image(
                                fit: BoxFit.fill,
                                image: AssetImage('assets/noimage.png'),
                              ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
          // button untuk tambah dan kurang makanan
          addRemoveQuantity(context, widget.isSell, widthScreen)
        ],
      ),
    );
  }

  Future<dynamic> modalShowMenu(BuildContext context, bool isSell) {
    return showModalBottomSheet(
      backgroundColor: backgroundColor.withOpacity(0),
      isScrollControlled: true,
      context: context,
      builder: (context) {
        return ShowMenuModal(
          imageUrl: widget.imageMedium,
          namaMenu: widget.namaMenu,
          hargaMenu: widget.hargaFix,
          isHavevariant: widget.isHaveVariant,
          description: widget.description,
          id: widget.id,
          variantCat: widget.variantCat,
          isSell: isSell,
        );
      },
    );
  }

  Container addRemoveQuantity(
      BuildContext context, bool isSell, double widthScreen) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.06,
      // color: Colors.blue,
      child: BlocBuilder<OrdersBloc, List<Orders>>(
        builder: (context, list) {
          int indexListOrderan =
              list.indexWhere((listOrderan) => listOrderan.id == widget.id);
          int initialValue;
          if (indexListOrderan != -1) {
            initialValue = list[indexListOrderan].totalItem;
          } else {
            initialValue = 0;
          }
          return Row(
            // mainAxisAlignment: MainAxisAlignment.end,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                padding: EdgeInsets.only(right: widthScreen * 0.03),
                width: widthScreen * 0.65,
                // color: Colors.red,
                child: (initialValue > 0 && !widget.isHaveVariant)
                    ? Align(
                        alignment: Alignment.centerRight,
                        child: noteMenu(
                          context,
                          list[indexListOrderan].note,
                          initialValue,
                          fromMenu,
                          list: list,
                          id: widget.id,
                          namaMenu: widget.namaMenu,
                          hargaFix: widget.hargaFix,
                          imageUrl: widget.imageUrl,
                        ),
                      )
                    : const SizedBox(),
              ),
              Container(
                // width: widthScreen * 0.27,
                width: widthScreen * 0.25,
                // color: Colors.red,
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        if (isSell) {
                          if (widget.isHaveVariant) {
                            if (indexListOrderan == -1) {
                              context
                                  .read<OrderVariantTemporaryBloc>()
                                  .insertDataVariant(
                                      widget.id,
                                      widget.hargaFix,
                                      1,
                                      []); // check pada bloc untuk mengethui list arraynya
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (_) => VariantCat(
                                            namaMenu: widget.namaMenu,
                                            variantCategories:
                                                widget.variantCat,
                                            initPrice: widget.hargaFix,
                                            idItem: widget.id,
                                            imageUrl: widget.imageUrl,
                                            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: widget.variantCat,
                                  );
                                },
                              );
                            }
                          } else {
                            if (initialValue == 0) {
                              initialValue += 1;
                              context.read<OrdersBloc>().insertData(
                                [
                                  [
                                    widget.id,
                                    widget.namaMenu,
                                    initialValue,
                                    widget.hargaFix,
                                    list,
                                    widget.imageUrl,
                                    orderVariants,
                                    widget.hargaFix,
                                    (indexListOrderan != -1)
                                        ? list[indexListOrderan].note
                                        : ''
                                  ]
                                ],
                              );
                              // setState(() {});
                            }
                          }
                        }
                      },
                      child: Container(
                          decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.circular(roundedButton),
                              color: (!isSell)
                                  ? Colors.grey
                                  : (initialValue == 0 &&
                                          widget.isHaveVariant == false)
                                      ? buttonColor
                                      : (initialValue >= 0 &&
                                              widget.isHaveVariant == true)
                                          ? buttonColor
                                          : null),
                          margin: (initialValue > 0)
                              ? EdgeInsets.only(
                                  top:
                                      MediaQuery.of(context).size.height * 0.01,
                                  bottom:
                                      MediaQuery.of(context).size.height * 0.01)
                              : EdgeInsets.only(
                                  top:
                                      MediaQuery.of(context).size.height * 0.01,
                                  bottom: MediaQuery.of(context).size.height *
                                      0.01),
                          width: widthScreen * 0.25,
                          child: AnimatedSwitcher(
                            duration: Duration(milliseconds: animatedTime),
                            transitionBuilder: (child, animation) =>
                                ScaleTransition(scale: animation, child: child),
                            child: (initialValue > 0 &&
                                    widget.isHaveVariant == false)
                                ? Row(
                                    key: const Key('3'),
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                    children: [
                                      // Icon(Icons.note_add),
                                      GestureDetector(
                                        onTap: () {
                                          if (initialValue > 0) {
                                            initialValue -= 1;
                                            context
                                                .read<OrdersBloc>()
                                                .insertData(
                                              [
                                                [
                                                  widget.id,
                                                  widget.namaMenu,
                                                  initialValue,
                                                  widget.hargaFix,
                                                  list,
                                                  widget.imageUrl,
                                                  orderVariants,
                                                  widget.hargaFix,
                                                  (indexListOrderan != -1)
                                                      ? list[indexListOrderan]
                                                          .note
                                                      : ''
                                                ]
                                              ],
                                            );
                                            // setState(() {});
                                          }
                                        },
                                        // child: Icon(
                                        //   Icons.remove_circle_outline_rounded,
                                        //   color: buttonColor,
                                        // ),
                                        child: Container(
                                          width: widthScreen * 0.06,
                                          color: backgroundColor,
                                          child: Align(
                                            alignment: Alignment.center,
                                            child: fontAwesome(
                                              context,
                                              minusCircle,
                                              minusCircleSize,
                                              color: buttonColor,
                                            ),
                                          ),
                                        ),
                                      ),
                                      Container(
                                        // width: widthScreen * 0.13,
                                        width: widthScreen * 0.13,
                                        // color: Colors.blue,
                                        child: Align(
                                          alignment: Alignment.center,
                                          child: defaultText(
                                            context,
                                            initialValue.toString(),
                                            style: textStyleNormalFont(context),
                                          ),
                                        ),
                                      ),
                                      GestureDetector(
                                        onTap: () {
                                          initialValue += 1;
                                          context.read<OrdersBloc>().insertData(
                                            [
                                              [
                                                widget.id,
                                                widget.namaMenu,
                                                initialValue,
                                                widget.hargaFix,
                                                list,
                                                widget.imageUrl,
                                                orderVariants,
                                                widget.hargaFix,
                                                (indexListOrderan != -1)
                                                    ? list[indexListOrderan]
                                                        .note
                                                    : '',
                                              ]
                                            ],
                                          );
                                          // setState(() {});
                                        },
                                        child: Container(
                                          width: widthScreen * 0.06,
                                          color: backgroundColor,
                                          child: Align(
                                            alignment: Alignment.center,
                                            child: fontAwesome(
                                              context,
                                              plusCicle,
                                              plusCicleSize,
                                              color: buttonColor,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  )
                                : addItem(context, widget.isHaveVariant, list,
                                    widget.id, indexListOrderan, isSell),
                          )),
                    ),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  Center addItem(BuildContext context, bool isHaveVariant, List<Orders> list,
      String id, int indexListOrderan, bool isSell) {
    if (isHaveVariant) {
      int totalItem = 0;
      if (indexListOrderan != -1) {
        if (list[indexListOrderan].orderDetail.isNotEmpty) {
          for (int d = 0; d < list[indexListOrderan].orderDetail.length; d++) {
            totalItem += list[indexListOrderan].orderDetail[d].totalItem;
          }
        }
      }
      if (totalItem == 0 && isSell == true) {
        return Center(
          key: const Key('3'),
          child: textAddButton(context, "Tambah"),
        );
      } else if (totalItem == 0 && isSell == false) {
        return Center(
          key: const Key('3'),
          child: textAddButton(context, "Habis"),
        );
      } else {
        String item = 'Item';
        if (totalItem > 1) {
          item = "Items";
        }
        return Center(
            key: const Key('3'),
            child: defaultText(
              context,
              "$totalItem $item",
              style: textStyleNormalFont(
                context,
                color: textInButton,
              ),
            ));
      }
    } else {
      if (isSell) {
        return Center(
          key: const Key('3'),
          child: textAddButton(context, "Tambah"),
        );
      } else {
        return Center(
          key: const Key('3'),
          child: textAddButton(context, "Habis"),
        );
      }
    }
  }
}
