// ignore_for_file: sized_box_for_whitespace

import 'package:byod/helper/prefs.dart';
import 'package:byod/models/filter_menu.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../api/api.dart';
import '../../bloc/view_bill.dart';
import '../../helper/helper.dart';
import '../../helper/widget/button_dialog.dart';
import '../../helper/widget/note_modal_bottom_sheet.dart';
import '../../helper/widget/plus_minus_button.dart';
import '../../helper/widget/style.dart';
import '../../models/bill.dart';
import '../../models/bill_detail.dart';
import 'view_bill_new.dart';

class OrderViewBillNew extends StatefulWidget {
  final BillDetail billDetail;
  final Bill bill;
  final bool lastItem;
  final bool isHistory;
  final int tableStatus;
  const OrderViewBillNew({
    Key? key,
    required this.billDetail,
    required this.isHistory,
    required this.bill,
    this.lastItem = false,
    required this.tableStatus,
  }) : super(key: key);

  @override
  State<OrderViewBillNew> createState() => _OrderViewBillNewState();
}

class _OrderViewBillNewState extends State<OrderViewBillNew> {
  void ontapOkDelete() {
    Api.deleteOrderDetail(widget.billDetail.id).then((value) {
      Navigator.pop(context);
      if (value == true) {
        Navigator.pushReplacement(
            context, MaterialPageRoute(builder: (_) => const ViewBillNew()));
      }
    });
  }

  void ontapCancelDelete() {
    Navigator.pop(context);
  }

  void changeOrderDetail(
    BuildContext context,
    String id,
    int initialValue,
    String notes,
  ) {
    Api.changeOrderDetail(
      context,
      id,
      initialValue,
      notes,
    ).then((value) {
      context.read<ViewBillBloc>().getBill();
    });
    // Api.deleteOrderDetail(widget.billDetail.id).then((value) {
    //   Navigator.pop(context);
    //   if (value == true) {
    //     Navigator.pushReplacement(
    //         context, MaterialPageRoute(builder: (_) => const ViewBill()));
    //   }
    // });
  }

  late int initialValue;
  late int amount;
  late int amountPeritem;
  late String noteDetail;

  @override
  void initState() {
    //** intial value for quantity order */
    initialValue = widget.billDetail.quantity;
    var perItem =
        amountParseToInt(widget.billDetail.total) / widget.billDetail.quantity;
    amountPeritem = perItem.toInt();
    amount = amountPeritem * widget.billDetail.quantity;
    //** intial value for quantity order */
    noteDetail = widget.billDetail.notes;
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  void minus() {
    if (initialValue > 1) {
      setState(() {
        initialValue -= 1;
        amount = initialValue * amountPeritem;
      });
      changeOrderDetail(
          context, widget.billDetail.id, initialValue, widget.billDetail.notes);
    } else {
      deleteOrder(context, widget.billDetail.menuName, ontapOkDelete,
          ontapCancelDelete);
    }
  }

  void plus() {
    setState(() {
      initialValue += 1;
      amount = initialValue * amountPeritem;
    });
    // await Api.changeOrderDetail(
    //   context,
    //   widget.billDetail.id,
    //   initialValue,
    //   widget.billDetail.notes,
    // );
    changeOrderDetail(
        context, widget.billDetail.id, initialValue, widget.billDetail.notes);
  }

  @override
  Widget build(BuildContext contextOrderViewBill) {
    double paddingLeftRightBill = 32;
    int paymentMode = getPaymentMode();
    String itemQuantityString;
    if (widget.billDetail.quantity > 1) {
      itemQuantityString = '${widget.billDetail.quantity} items';
    } else {
      itemQuantityString = '${widget.billDetail.quantity} item';
    }
    return Container(
      // padding: const EdgeInsets.symmetric(horizontal: 32),
      padding: EdgeInsets.only(
        top: 18,
        bottom: (widget.lastItem) ? 11 : 0,
      ),
      width: double.infinity,
      color: backgroundWhite,
      child: Column(
        children: [
          Container(
            width: double.infinity,
            // color: Colors.red,
            child: Column(
              children: [
                Container(
                  padding: EdgeInsets.only(
                      left: paddingLeftRightBill, right: paddingLeftRightBill),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(5),
                        child: (widget.billDetail.imageUrl != '')
                            ? Image(
                                width: 80,
                                height: 80,
                                fit: BoxFit.fill,
                                image: NetworkImage(
                                  widget.billDetail.imageUrl,
                                ),
                              )
                            : const Image(
                                width: 80,
                                height: 80,
                                fit: BoxFit.fill,
                                image: AssetImage(
                                  'assets/noimage.png',
                                ),
                              ),
                      ),
                      const SizedBox(
                        width: 8,
                      ),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            defaultText(
                              context,
                              widget.billDetail.menuName,
                              maxLines: 2,
                              overFlow: TextOverflow.ellipsis,
                              style: menuNameListViewBill(),
                            ),
                            defaultText(
                              context,
                              getOrderStatus(widget.billDetail.orderStatus),
                              style: viewbillStyle(
                                font: 12,
                                fontWeight: FontWeight.w300,
                                color: getOrderStatusColor(
                                    widget.billDetail.orderStatus),
                              ),
                            ),
                            const SizedBox(
                              height: 6,
                            ),
                            defaultText(
                              context,
                              (paymentMode == openBill)
                                  ? 'Rp ${formatNumber().format(amountParseToInt(widget.billDetail.total))} | $itemQuantityString '
                                  : 'Rp ${formatNumber().format(amountParseToInt(widget.billDetail.total))}',
                              style: viewbillStyle(
                                font: 12,
                                fontWeight: FontWeight.w300,
                              ),
                            ),
                            for (int k = 0;
                                k < widget.billDetail.variant.length;
                                k++)
                              // Container(
                              //   width: MediaQuery.of(context).size.width -
                              //       paddingLeftRightBill -
                              //       paddingLeftRightBill -
                              //       88, // 88 itu besar image dan space sized box pemisah
                              //   color: Colors.red,
                              //   child: Row(
                              //     mainAxisAlignment: MainAxisAlignment.start,
                              //     children: [
                              //       defaultText(
                              //         context,
                              //         "${widget.billDetail.variant[k].caption} : ",
                              //         style: viewbillStyle(
                              //           font: 12,
                              //           fontWeight: FontWeight.w300,
                              //         ),
                              //       ),
                              //       defaultText(
                              //         context,
                              //         widget.billDetail.variant[k].variantName
                              //             .join(', '),
                              //         style: viewbillStyle(
                              //           font: 12,
                              //           fontWeight: FontWeight.w300,
                              //         ),
                              //       )
                              //     ],
                              //   ),
                              // ),
                              Container(
                                width: MediaQuery.of(context).size.width -
                                    paddingLeftRightBill -
                                    paddingLeftRightBill -
                                    88,
                                child: defaultText(
                                  context,
                                  "${widget.billDetail.variant[k].caption} : ${widget.billDetail.variant[k].variantName.join(', ')}",
                                  // maxLines: 2,
                                  // overFlow: TextOverflow.ellipsis,
                                  style: viewbillStyle(
                                    font: 12,
                                    fontWeight: FontWeight.w300,
                                  ),
                                ),
                              ),
                            const SizedBox(
                              height: 6,
                            ),
                            (widget.billDetail.notes != '')
                                ? defaultText(
                                    context,
                                    'Catatan: ${widget.billDetail.notes}',
                                    maxLines: 2,
                                    overFlow: TextOverflow.ellipsis,
                                    style: viewbillStyle(
                                      font: 12,
                                      fontWeight: FontWeight.w300,
                                    ),
                                  )
                                : const SizedBox(),
                          ],
                        ),
                      ),
                      (isRemoveButtonBillShow(
                              widget.bill.state, widget.billDetail.orderStatus))
                          ? const SizedBox(
                              width: 5,
                            )
                          : const SizedBox(),
                      (isRemoveButtonBillShow(
                              widget.bill.state, widget.billDetail.orderStatus))
                          ? GestureDetector(
                              onTap: () {
                                deleteOrder(context, widget.billDetail.menuName,
                                    ontapOkDelete, ontapCancelDelete);
                              },
                              child: Container(
                                color: backgroundWhite,
                                child: fontAwesomeNew(
                                  trahsIcon,
                                  trahsIconSize,
                                  color: dangerColor,
                                ),
                              ),
                            )
                          : const SizedBox()
                    ],
                  ),
                ),
              ],
            ),
          ),
          isVisibleAddRemoveQuantityButtonCheckout(widget.isHistory,
                  widget.billDetail.orderStatus, widget.bill.state)
              ? Container(
                  padding: EdgeInsets.only(
                      left: paddingLeftRightBill, right: paddingLeftRightBill),
                  child: const Divider(
                    thickness: 1,
                    color: backgroundColor,
                  ),
                )
              : const SizedBox(),
          isVisibleAddRemoveQuantityButtonCheckout(widget.isHistory,
                  widget.billDetail.orderStatus, widget.bill.state)
              ? const SizedBox(
                  height: 11,
                )
              : const SizedBox(),
          isVisibleAddRemoveQuantityButtonCheckout(widget.isHistory,
                  widget.billDetail.orderStatus, widget.bill.state)
              ? Container(
                  padding: EdgeInsets.only(
                    left: paddingLeftRightBill,
                    right: paddingLeftRightBill,
                  ),
                  child: Row(
                    children: [
                      GestureDetector(
                        onTap: () {
                          if (iscanTapAddRemoveQtyViewBill(widget.bill.state) ==
                              true) {
                            FocusScopeNode currentFocus =
                                FocusScope.of(context);

                            if (!currentFocus.hasPrimaryFocus) {
                              currentFocus.unfocus();
                            }
                            showModalBottomSheet(
                              backgroundColor: backgroundColor,
                              isScrollControlled: true,
                              context: context,
                              builder: (context) {
                                return NoteModalBottomSheet(
                                  noteController: TextEditingController(
                                      text: widget.billDetail.notes),
                                  initialValue: initialValue,
                                  orderVariants: const [],
                                  menuItem: FilterMenu(
                                      id: '',
                                      name: '',
                                      price: '',
                                      originalPrice: '',
                                      imageUrlMedium: '',
                                      imageUrlThumbnail: '',
                                      isSell: false,
                                      type: typeMenu,
                                      categoryName: '',
                                      categoryId: '',
                                      description: '',
                                      groupName: '',
                                      groupId: ''),
                                  listOrders: const [],
                                  from: fromBill,
                                  idOrderan: widget.billDetail.id,
                                  contextFrom: contextOrderViewBill,
                                );
                              },
                            );
                          }
                        },
                        child: Container(
                          height: 30,
                          width: 98,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(21),
                            color: (iscanTapAddRemoveQtyViewBill(
                                        widget.bill.state) ==
                                    true)
                                ? buttonColor
                                : disabledColor,
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              const Image(
                                height: 16,
                                width: 16,
                                image: AssetImage('assets/icons/note.png'),
                              ),
                              const SizedBox(
                                width: 10,
                              ),
                              Container(
                                height: 16,
                                child: Center(
                                  child: defaultText(
                                    context,
                                    (widget.billDetail.notes != '')
                                        ? 'Ubah'
                                        : 'Catatan',
                                    style: noteViewBill(
                                      color: textInButton,
                                    ),
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                      const Spacer(),
                      PlusMinusButton(
                        initialValue: widget.billDetail.quantity,
                        plus: plus,
                        minus: minus,
                        isCanTap:
                            iscanTapAddRemoveQtyViewBill(widget.bill.state),
                      ),
                      const SizedBox(
                        width: 12,
                      )
                    ],
                  ),
                )
              : const SizedBox(),
          (widget.lastItem)
              ? const SizedBox(
                  height: 11,
                )
              : const SizedBox(),
          (!widget.lastItem)
              ? Container(
                  padding: (isVisibleAddRemoveQuantityButtonCheckout(
                          widget.isHistory,
                          widget.billDetail.orderStatus,
                          widget.bill.state))
                      ? null
                      : const EdgeInsets.only(
                          top: 15,
                        ),
                  child: const Divider(
                    thickness: 2,
                    color: backgroundColorViewBill,
                  ),
                )
              : const SizedBox()
        ],
      ),
    );
  }

  Future<dynamic> deleteOrder(BuildContext context, String menuName,
      void Function() ontapOkDelete, void Function() ontapCancelDelete) {
    return buttonDialogGlobal(
      context,
      'Konfirmasi Delete Order',
      'Yakin menghapus orderan $menuName ?',
      'Hapus',
      'Batal',
      ontapOkDelete,
      ontapCancelDelete,
      okButtonColor: buttonColor,
      cancelButtonColor: cancelColorButton,
    );
  }
}
