// ignore_for_file: sized_box_for_whitespace, avoid_unnecessary_containers

import 'package:byod/bloc/order_variant_temporary.dart';
import 'package:byod/bloc/order_variant_value.dart';
import 'package:byod/helper/helper.dart';
import 'package:byod/helper/widget/style.dart';
import 'package:byod/main.dart';
import 'package:byod/models/order_details.dart';
import 'package:byod/models/variant_categories.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 '../../models/order_variants.dart';
import '../../models/orders.dart';
import 'variant.dart';

// ignore: must_be_immutable
class VariantCat extends StatefulWidget {
  String namaMenu;
  int initPrice;
  String idItem;
  String imageUrl;
  List<VariantCategories> variantCategories;
  List<Orders> listCurrentOrder;
  OrderDetail
      orderDetail; // niatnya buat edit custom order, tapi lagi pusing, nanti dulu deh, user kalau mau edit harus order ulang dulu aja
  VariantCat(
      {Key? key,
      required this.namaMenu,
      required this.variantCategories,
      required this.initPrice,
      required this.idItem,
      required this.imageUrl,
      required this.listCurrentOrder,
      required this.orderDetail})
      : super(key: key);

  @override
  State<VariantCat> createState() => _VariantCatState();
}

class _VariantCatState extends State<VariantCat> {
  final viewInsets = EdgeInsets.fromWindowPadding(
      WidgetsBinding.instance.window.viewInsets,
      WidgetsBinding.instance.window.devicePixelRatio);
  // int initialValue = 1;
  // List<OrderVariant> orderVariants = [];
  final noteCatController = TextEditingController();
  @override
  void initState() {
    context
        .read<OrderVariantValueBloc>()
        .setOrderVariant('', '', '', 0, 0, [], '');
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    double widthScreen = responsiveWidthScreen(context);
    double currentScreen = MediaQuery.of(context).size.width;
    double maxWidthScreen = getMaxWidthScreen(context, useResponsive);
    FocusScopeNode currentFocus = FocusScope.of(context);
    List<OrderVariant> listOrderVariantDefault = [];
    for (int d = 0; d < widget.variantCategories.length; d++) {
      if (widget.variantCategories[d].type == typeAutoInsert) {
        for (int i = 0; i < widget.variantCategories[d].variant.length; i++) {
          OrderVariant defaultOrderVariantAutoInsert = OrderVariant(
            categoryId: widget.variantCategories[d].id,
            id: widget.variantCategories[d].variant[i].id,
            name: widget.variantCategories[d].variant[i].name,
            price:
                amountParseToInt(widget.variantCategories[d].variant[i].price),
            type: typeAutoInsert,
            caption: widget.variantCategories[d].caption,
          );
          int index = listOrderVariantDefault.indexWhere((orderVariant) =>
              orderVariant.id == widget.variantCategories[d].variant[i].id);
          if (index == -1) {
            listOrderVariantDefault.add(defaultOrderVariantAutoInsert);
          }
          context.read<OrderVariantValueBloc>().setOrderVariant(
                widget.variantCategories[d].id,
                widget.variantCategories[d].variant[i].id,
                widget.variantCategories[d].variant[i].name,
                amountParseToInt(widget.variantCategories[d].variant[i].price),
                typeAutoInsert,
                listOrderVariantDefault,
                widget.variantCategories[d].caption,
              );
        }
      }
    }
    return SafeArea(
        child: Scaffold(
      backgroundColor: backgroundColor,
      body: BlocBuilder<OrderVariantValueBloc, List<OrderVariant>>(
        builder: (context, orderVariants) {
          return BlocBuilder<OrderVariantTemporaryBloc, List<dynamic>>(
            builder: (context, 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: coreVariantCat(
                  widthScreen,
                  context,
                  currentFocus,
                  initialValue,
                  itemId,
                  satuanPrice,
                  orderVariants,
                  totalPrice,
                  maxWidthScreen,
                ),
                widthScreen: currentScreen,
                isCoreLayout: true,
              );
              // return coreVariantCat(widthScreen, context, currentFocus,
              //     initialValue, itemId, satuanPrice, orderVariants, totalPrice);
            },
          );
        },
      ),
    ));
  }

  Container coreVariantCat(
    double widthScreen,
    BuildContext context,
    FocusScopeNode currentFocus,
    initialValue,
    itemId,
    satuanPrice,
    List<OrderVariant> orderVariants,
    int totalPrice,
    double maxWidthScreen,
  ) {
    return Container(
      width: (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
      // margin: EdgeInsets.all(widthScreen * 0.01),
      padding: EdgeInsets.only(
          top: MediaQuery.of(context).size.height * 0.015,
          left: widthScreen * 0.04,
          right: widthScreen * 0.04),
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(15)),
      child: SingleChildScrollView(
        child: Column(
          children: [
            Stack(
              children: [
                Column(
                  children: [
                    customAppbar(
                      context,
                      widthScreen,
                      maxWidthScreen,
                    ),
                    Container(
                      padding: EdgeInsets.only(
                          bottom: MediaQuery.of(context).size.height * 0.16),
                      height: MediaQuery.of(context).size.height * 0.92,
                      width: (widthScreen > maxWidthScreen)
                          ? maxWidthScreen
                          : widthScreen,
                      // color: Colors.red,
                      child: ListView(
                        children: [
                          ListView.builder(
                              physics:
                                  const NeverScrollableScrollPhysics(), // to disable GridView's scrolling
                              shrinkWrap: true,
                              itemCount: widget.variantCategories.length,
                              itemBuilder: ((context, index) {
                                // List<String> _variants = [];
                                return Container(
                                  width: double.infinity,
                                  // color: Colors.blue,
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      (index > 0)
                                          ? Divider(
                                              height: MediaQuery.of(context)
                                                      .size
                                                      .height *
                                                  0.05,
                                              color: disabledColor,
                                            )
                                          : const SizedBox(),
                                      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: textStyleMenuList(context),
                                            ),
                                            defaultText(
                                              context,
                                              (widget.variantCategories[index]
                                                          .type ==
                                                      typeMandatory)
                                                  ? 'Pilih Salah Satu'
                                                  : (widget
                                                              .variantCategories[
                                                                  index]
                                                              .type ==
                                                          typeAutoInsert)
                                                      ? 'Sudah termasuk'
                                                      : 'Optional',
                                              style: textStyleNormalFont(
                                                context,
                                                isBold: true,
                                                color: Colors.black54,
                                              ),
                                            )
                                          ],
                                        ),
                                      ),
                                      Divider(
                                        height:
                                            MediaQuery.of(context).size.height *
                                                0.05,
                                        color: disabledColor,
                                      ),
                                      Variant(
                                        variants: widget
                                            .variantCategories[index].variant,
                                        captioncategories: widget
                                            .variantCategories[index].caption,
                                        type: widget
                                            .variantCategories[index].type,
                                        initPrice: widget.initPrice,
                                        idCategory:
                                            widget.variantCategories[index].id,
                                        orderDetail: widget.orderDetail,
                                      ),
                                    ],
                                  ),
                                );
                              })),
                          SizedBox(
                            height: MediaQuery.of(context).size.height * 0.05,
                          ),
                          defaultText(
                            context,
                            "Note :",
                            style: textStyleNormalFont(
                              context,
                              font: menuFont,
                            ),
                          ),
                          SizedBox(
                            height: MediaQuery.of(context).size.height * 0.03,
                          ),
                          Container(
                            height: MediaQuery.of(context).size.height * 0.1,
                            width: widthScreen * 0.86,
                            // color: Colors.red,
                            child: TextField(
                              maxLength: maxLengthTextField,
                              maxLines: 2,
                              autofocus: false,
                              keyboardType: TextInputType.text,
                              controller: noteCatController,
                              style: textStyleNormalFont(context),
                              decoration: InputDecoration(
                                hintText: placeHolderNote,
                                hintStyle: TextStyle(
                                  color: Colors.grey,
                                  fontSize: MediaQuery.of(context).size.height *
                                      normalFont,
                                ),
                              ),
                            ),
                          ),
                          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:
                        MediaQuery.of(context).size.height * positionedBottom,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        addRemoveQuantity(context, initialValue, itemId,
                            satuanPrice, currentFocus, widthScreen),
                        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) {
                              context.read<OrdersBloc>().insertData([
                                [
                                  widget.idItem,
                                  widget.namaMenu,
                                  initialValue,
                                  widget.initPrice,
                                  widget.listCurrentOrder,
                                  widget.imageUrl,
                                  orderVariants,
                                  totalPrice,
                                  (noteCatController.text.isEmpty)
                                      ? ''
                                      : noteCatController.text
                                ]
                              ], context);
                              Navigator.pop(context);
                            } else {
                              EasyLoading.showToast(
                                  'Masih ada variant yang belum dipilih');
                            }
                          },
                          child: buttonBottom(
                            context,
                            "Tambahkan - Rp ${formatNumber().format(totalPrice)}",
                            buttonColor,
                            0.92,
                          ),
                        ),
                      ],
                    ))
              ],
            ),
          ],
        ),
      ),
    );
  }

  Container addRemoveQuantity(BuildContext context, initialValue, itemId,
      satuanPrice, FocusScopeNode currentFocus, double widthScreen) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.08,
      width: widthScreen * 0.92,
      color: backgroundColor,
      child: Row(
        // mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Container(
            width: widthScreen * 0.52,
            child: defaultText(
              context,
              "Jumlah Order",
              style: textStyleNormalFont(context),
            ),
          ),
          Container(
            width: widthScreen * 0.4,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                const SizedBox(width: 15),
                GestureDetector(
                  onTap: () {
                    if (initialValue > 1) {
                      initialValue += -1;
                      context
                          .read<OrderVariantTemporaryBloc>()
                          .insertDataVariant(
                              itemId, satuanPrice, initialValue, []);
                    }
                  },
                  child: Container(
                    width: widthScreen * 0.1,
                    color: backgroundColor,
                    child: Align(
                      alignment: Alignment.center,
                      child: fontAwesome(
                        context,
                        minusCircle,
                        minusCircleSize,
                        color: (initialValue > 1) ? buttonColor : Colors.grey,
                      ),
                    ),
                  ),
                ),
                SizedBox(width: widthScreen * 0.05),
                defaultText(
                  context,
                  initialValue.toString(),
                  style: textStyleNormalFont(context),
                ),
                SizedBox(width: widthScreen * 0.05),
                GestureDetector(
                  onTap: () {
                    initialValue += 1;
                    context.read<OrderVariantTemporaryBloc>().insertDataVariant(
                        itemId, satuanPrice, initialValue, []);
                  },
                  child: Container(
                    width: widthScreen * 0.1,
                    color: backgroundColor,
                    child: Align(
                      alignment: Alignment.center,
                      child: fontAwesome(
                        context,
                        plusCicle,
                        plusCicleSize,
                        color: buttonColor,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Container customAppbar(
      BuildContext context, double widthScreen, double maxWidthScreen) {
    // FocusScopeNode currentFocus = FocusScope.of(context);
    return Container(
      height: MediaQuery.of(context).size.height * 0.05,
      width: (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
      // color: Colors.amber,
      child: Row(
        children: [
          GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: Container(
              // color: Colors.white,
              height: double.infinity,
              width: widthScreen * 0.1,
              // child: const Icon(Icons.arrow_back_ios_new_rounded),
              child: Align(
                alignment: Alignment.center,
                child: fontAwesome(
                  context,
                  backIcon,
                  backIconSize,
                ),
              ),
            ),
          ),
          Container(
            // color: Colors.red,
            height: double.infinity,
            width: widthScreen * 0.81,
            child: Align(
              alignment: Alignment.centerLeft,
              child: defaultText(
                context,
                widget.namaMenu,
                overFlow: TextOverflow.ellipsis,
                style: textStyleMenuList(context),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
