// 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_detail.dart';
import 'view_bill_new.dart';

class OrderViewBillNew extends StatefulWidget {
  final BillDetail billDetail;
  final bool lastItem;
  final bool isHistory;
  final int tableStatus;
  const OrderViewBillNew({
    Key? key,
    required this.billDetail,
    required this.isHistory,
    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.start,
                      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,
                              ),
                            ),
                            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(),
                          ],
                        ))
                      ],
                    ),
                  ),
                ],
              ),
            ),
            isVisibleAddRemoveQuantityButtonCheckout(
                    widget.isHistory, widget.billDetail.orderStatus)
                ? Container(
                    padding: EdgeInsets.only(
                        left: paddingLeftRightBill,
                        right: paddingLeftRightBill),
                    child: const Divider(
                      thickness: 1,
                      color: backgroundColor,
                    ),
                  )
                : const SizedBox(),
            isVisibleAddRemoveQuantityButtonCheckout(
                    widget.isHistory, widget.billDetail.orderStatus)
                ? const SizedBox(
                    height: 11,
                  )
                : const SizedBox(),
            isVisibleAddRemoveQuantityButtonCheckout(
                    widget.isHistory, widget.billDetail.orderStatus)
                ? Container(
                    padding: EdgeInsets.only(
                        left: paddingLeftRightBill,
                        right: paddingLeftRightBill),
                    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: 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: ''),
                                  lisrOrders: const [],
                                  from: fromBill,
                                  idOrderan: widget.billDetail.id,
                                  contextFrom: contextOrderViewBill,
                                );
                              },
                            );
                          },
                          child: Container(
                            height: 30,
                            width: 98,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(21),
                              color: buttonColor,
                            ),
                            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,
                        ),
                        const SizedBox(
                          width: 12,
                        )
                      ],
                    ),
                  )
                : const SizedBox(),
            (widget.lastItem)
                ? const SizedBox(
                    height: 11,
                  )
                : const SizedBox(),
            (!widget.lastItem)
                ? 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,
    );
  }
}
