// ignore_for_file: sized_box_for_whitespace, must_be_immutable

import 'package:byod/helper/helper.dart';
import 'package:byod/helper/widget/button_modal.dart';
import 'package:byod/helper/widget/style.dart';
import 'package:byod/models/order_details.dart';
import 'package:byod/ui/home/variant_new.dart';
import 'package:byod/ui/screen_responsive.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../../bloc/order_bloc.dart';
import '../../bloc/order_variant_temporary.dart';
import '../../bloc/order_variant_value.dart';
import '../../helper/widget/plus_minus_button.dart';
import '../../main.dart';
import '../../models/order_variants.dart';
import '../../models/orders.dart';
import '../../models/variant_categories.dart';

class VariantCatNew extends StatefulWidget {
  final List<VariantCategories> variantCategories;
  final int initPrice;
  final String namaMenu;
  final String idItem;
  final List<Orders> listCurrentOrder;
  final String imageUrl;
  const VariantCatNew({
    Key? key,
    required this.variantCategories,
    required this.initPrice,
    required this.namaMenu,
    required this.idItem,
    required this.listCurrentOrder,
    required this.imageUrl,
  }) : super(key: key);

  @override
  State<VariantCatNew> createState() => _VariantCatNewState();
}

class _VariantCatNewState extends State<VariantCatNew> {
  final noteCatController = TextEditingController();

  OrderDetail orderDetail = OrderDetail(
    allIdVariant: '',
    totalItem: 0,
    totalHarga: 0,
    note: '',
    orderVariant: [],
  );

  @override
  void initState() {
    context
        .read<OrderVariantValueBloc>()
        .setOrderVariant('', '', '', 0, 0, [], '');
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    double widthScreen = responsiveWidthScreen(context);
    return SafeArea(
        child: GestureDetector(
      onTap: () {
        if (!currentFocus.hasPrimaryFocus) {
          currentFocus.unfocus();
        }
      },
      child: Scaffold(
        backgroundColor: backgroundColor,
        body: BlocBuilder<OrderVariantValueBloc, List<OrderVariant>>(
          builder: (contextVB, orderVariants) {
            return BlocBuilder<OrderVariantTemporaryBloc, List<dynamic>>(
              builder: (contextTmp, listOrders) {
                var listOrder = listOrders[0];
                var itemId = listOrder[0];
                var satuanPrice = listOrder[1];
                int totalPrice;
                var initialValue = listOrder[2];
                // var listVariant = listOrder[3];
                if (orderVariants.isNotEmpty) {
                  // totalPrice = 0;
                  int priceVariant = 0;
                  for (int z = 0; z < orderVariants.length; z++) {
                    priceVariant += orderVariants[z].price;
                  }
                  totalPrice = (listOrder[1] + priceVariant) * initialValue;
                } else {
                  totalPrice = listOrder[1] * initialValue;
                }
                return ScreenResponsive(
                  widget: CoreVariant(
                    widthScreen: widthScreen,
                    widget: widget,
                    orderDetail: orderDetail,
                    currentFocus: currentFocus,
                    initialValue: initialValue,
                    itemId: itemId,
                    satuanPrice: satuanPrice,
                    totalPrice: totalPrice,
                    context: context,
                    orderVariants: orderVariants,
                    noteCatController: noteCatController,
                  ),
                  isCoreLayout: true,
                  widthScreen: MediaQuery.of(context).size.width,
                );
              },
            );
          },
        ),
      ),
    ));
  }
}

class CoreVariant extends StatelessWidget {
  CoreVariant({
    Key? key,
    required this.widthScreen,
    required this.widget,
    required this.orderDetail,
    required this.currentFocus,
    required this.initialValue,
    required this.itemId,
    required this.satuanPrice,
    required this.totalPrice,
    required this.context,
    required this.orderVariants,
    required this.noteCatController,
  }) : super(key: key);

  final double widthScreen;
  final VariantCatNew widget;
  final OrderDetail orderDetail;
  final FocusScopeNode currentFocus;
  late int initialValue;
  final String itemId;
  final int satuanPrice;
  final int totalPrice;
  final BuildContext context;
  final List<OrderVariant> orderVariants;
  final TextEditingController noteCatController;
  void plus() {
    initialValue += 1;
    context
        .read<OrderVariantTemporaryBloc>()
        .insertDataVariant(itemId, satuanPrice, initialValue, []);
  }

  void minus() {
    if (initialValue > 1) {
      initialValue += -1;
      context
          .read<OrderVariantTemporaryBloc>()
          .insertDataVariant(itemId, satuanPrice, initialValue, []);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widthScreen,
      child: Stack(
        children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: paddingLeftRight),
            child: Column(
              children: [
                Container(
                  margin: const EdgeInsets.only(
                    top: 15,
                    bottom: 20,
                  ),
                  child: Row(
                    children: [
                      GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                        },
                        child: Container(
                          width: 24,
                          height: 24,
                          child: Center(
                            child: fontAwesomeNew(
                              arrowBack,
                              arrowBackSize,
                            ),
                          ),
                        ),
                      ),
                      const SizedBox(
                        width: 16,
                      ),
                      Center(
                        child: defaultText(
                          context,
                          widget.namaMenu,
                          maxLines: 1,
                          overFlow: TextOverflow.ellipsis,
                          style: appBarNameVariant(),
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: ListView(
                    children: [
                      ListView.builder(
                        physics:
                            const NeverScrollableScrollPhysics(), // to disable GridView's scrolling
                        shrinkWrap: true,
                        itemCount: widget.variantCategories.length,
                        itemBuilder: ((context, index) {
                          return VariantDetail(
                            widget: widget,
                            orderDetail: orderDetail,
                            index: index,
                          );
                        }),
                      ),
                      const SizedBox(
                        height: 74,
                      ),
                      defaultText(
                        context,
                        "Note :",
                        style: variantStyleText(
                          font: 20,
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                      const SizedBox(
                        height: 12,
                      ),
                      Container(
                        height: 35,
                        child: TextField(
                          controller: noteCatController,
                          maxLength: maxLengthTextField,
                          autofocus: false,
                          style: const TextStyle(
                            color: textColorBlack,
                            fontFamily: 'OpenSans',
                            fontSize: 10,
                            fontWeight: FontWeight.w400,
                          ),
                          textAlignVertical: TextAlignVertical.center,
                          decoration: InputDecoration(
                            counterText: "",
                            filled: true,
                            enabledBorder: OutlineInputBorder(
                              borderSide: const BorderSide(
                                width: 1,
                                color: textColorPlaceHolder,
                              ),
                              borderRadius: BorderRadius.circular(21),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderSide: const BorderSide(
                                width: 1,
                                color: textColorPlaceHolder,
                              ),
                              borderRadius: BorderRadius.circular(21),
                            ),
                            prefixIcon: const Image(
                              image: AssetImage('assets/icons/note-grey.png'),
                              color: textColorPlaceHolder,
                              height: 13.33,
                              width: 13.33,
                            ),
                            fillColor: backgroundColor,
                            contentPadding: EdgeInsets.zero,
                            hintText: placeHolderNote,
                            hintStyle: const TextStyle(
                              color: textColorPlaceHolder,
                              fontFamily: 'OpenSans',
                              fontSize: 10,
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(
                        height: MediaQuery.of(context).size.height * 0.03,
                      ),
                      (isExcelso)
                          ? (!currentFocus.hasPrimaryFocus)
                              ? SizedBox(
                                  height:
                                      MediaQuery.of(context).size.height * 0.5,
                                )
                              : const SizedBox()
                          : const SizedBox()
                    ],
                  ),
                )
              ],
            ),
          ),
          Positioned(
            bottom: 0,
            child: Container(
              padding: const EdgeInsets.symmetric(
                horizontal: paddingLeftRight,
              ),
              width: widthScreen,
              height: 118,
              decoration: const BoxDecoration(
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(16),
                  topRight: Radius.circular(16),
                ),
                color: backgroundWhite,
              ),
              child: Column(
                children: [
                  const SizedBox(
                    height: 21,
                  ),
                  Row(
                    children: [
                      defaultText(context, 'Jumlah Pesanan'),
                      const Spacer(),
                      PlusMinusButton(
                        initialValue: initialValue,
                        plus: plus,
                        minus: minus,
                        isFromVariant: true,
                      ),
                    ],
                  ),
                  const SizedBox(
                    height: 14,
                  ),
                  GestureDetector(
                    onTap: () {
                      bool prosesOrderan = true;
                      for (int y = 0;
                          y < widget.variantCategories.length;
                          y++) {
                        if (widget.variantCategories[y].type == typeMandatory) {
                          int index = orderVariants.indexWhere((order) =>
                              order.categoryId ==
                              widget.variantCategories[y].id);
                          if (index == -1) {
                            prosesOrderan = false;
                          }
                        }
                      }
                      if (prosesOrderan) {
                        Map<String, dynamic> insertData = {
                          'menu_id': widget.idItem,
                          'menu_name': widget.namaMenu,
                          'initvalue': initialValue,
                          'menu_price': widget.initPrice,
                          'old_order': widget.listCurrentOrder,
                          'image_url': widget.imageUrl,
                          'order_variant': orderVariants,
                          'note': (noteCatController.text.isEmpty)
                              ? ''
                              : noteCatController.text,
                          'total_price': totalPrice,
                        };
                        context.read<OrdersBloc>().insertData(insertData);
                        Navigator.pop(context);
                      } else {
                        EasyLoading.showToast(
                            'Masih ada variant yang belum dipilih');
                      }
                    },
                    child: ButtonComponent(
                        buttonColor: buttonColor,
                        teksButton:
                            'Tambahkan - Rp ${formatNumber().format(totalPrice)}'),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

class VariantDetail extends StatelessWidget {
  const VariantDetail({
    Key? key,
    required this.widget,
    required this.orderDetail,
    required this.index,
  }) : super(key: key);

  final VariantCatNew widget;
  final OrderDetail orderDetail;
  final int index;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(
                bottom: MediaQuery.of(context).size.height * 0.01,
                top: MediaQuery.of(context).size.height * 0.01),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                defaultText(
                  context,
                  widget.variantCategories[index].caption,
                  style: variantStyleText(),
                ),
                defaultText(
                  context,
                  (widget.variantCategories[index].type == typeMandatory)
                      ? 'Pilih Salah Satu'
                      : (widget.variantCategories[index].type == typeAutoInsert)
                          ? 'Sudah termasuk'
                          : 'Optional',
                  style: variantStyleText(
                    font: 12,
                    fontWeight: FontWeight.w300,
                  ),
                )
              ],
            ),
          ),
          const Divider(
            thickness: 0.5,
            color: textColorBlack,
          ),
          VariantNew(
            variants: widget.variantCategories[index].variant,
            captioncategories: widget.variantCategories[index].caption,
            type: widget.variantCategories[index].type,
            initPrice: widget.initPrice,
            idCategory: widget.variantCategories[index].id,
            orderDetail: orderDetail,
          ),
        ],
      ),
    );
  }
}
