// ignore_for_file: sized_box_for_whitespace, must_be_immutable

import 'dart:async';

import 'package:byod/helper/widget/button_dialog.dart';
import 'package:byod/models/bill_detail.dart';
import 'package:byod/ui/home/bottom_sheet_note.dart';
import 'package:byod/ui/screen_responsive.dart';
import 'package:byod/ui/viewbill/view_bill.dart';
import 'package:flutter/material.dart';

import '../../api/api.dart';
import '../../helper/helper.dart';
import '../../helper/widget/style.dart';

class OrderViewBill extends StatefulWidget {
  BillDetail billDetail;
  int itemKe;
  int itemCount;
  bool isFromPayment;
  int tableMode;
  int tableStatus;
  OrderViewBill(
      {Key? key,
      required this.billDetail,
      required this.itemKe,
      required this.itemCount,
      this.isFromPayment = false,
      this.tableMode = multiTable,
      required this.tableStatus})
      : super(key: key);

  @override
  State<OrderViewBill> createState() => _OrderViewBillState();
}

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

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

  void changeOrderDetail(
    BuildContext context,
    String id,
    int initialValue,
    String notes,
  ) {
    Api.changeOrderDetail(
      context,
      id,
      initialValue,
      notes,
    );
    // 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;
  bool isUserTapped = false;
  bool doActionApiBill = false;
  @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 */

    super.initState();
  }

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

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

    double maxWidthScreen = getMaxWidthScreen(context, useResponsive);
    // int totalItemBayar = amountParseToInt(widget.billDetail.total);
    // //** Buat custom height berdasarkan ada atau tidaknya note dan variant */
    // double heighContainerDefault = MediaQuery.of(context).size.height * 0.09;
    // double heighContainerAtas = MediaQuery.of(context).size.height * 0.09;
    // if (widget.billDetail.notes != '' && widget.billDetail.variant.isEmpty) {
    //   heighContainerAtas =
    //       heighContainerDefault + MediaQuery.of(context).size.height * 0.04;
    //   heighContainerDefault =
    //       heighContainerDefault + MediaQuery.of(context).size.height * 0.03;
    // } else if (widget.billDetail.notes != '' &&
    //     widget.billDetail.variant.isNotEmpty) {
    //   //**asumsi 1 text memiliki height untuk container 0.02 base on media query height */
    //   double oneVariantHeight = MediaQuery.of(context).size.height * 0.03;
    //   heighContainerAtas =
    //       (heighContainerDefault + MediaQuery.of(context).size.height * 0.04) +
    //           (widget.billDetail.variant.length * oneVariantHeight);
    //   heighContainerDefault =
    //       (heighContainerDefault + MediaQuery.of(context).size.height * 0.02) +
    //           (widget.billDetail.variant.length * oneVariantHeight);
    // } else {
    //   double oneVariantHeight = MediaQuery.of(context).size.height * 0.03;
    //   heighContainerAtas =
    //       (heighContainerDefault + MediaQuery.of(context).size.height * 0.02) +
    //           (widget.billDetail.variant.length * oneVariantHeight);
    //   heighContainerDefault = heighContainerDefault +
    //       (widget.billDetail.variant.length * oneVariantHeight);
    // }
    //** Buat custom height berdasarkan ada atau tidaknya note dan variant */

    // if (doActionApiBill) {
    //   Future.delayed(const Duration(milliseconds: 1500), () async {
    //     // if (doActionApiBill == true) {
    //     print("aaaaaa");
    //     // }
    //   });
    // }
    return ScreenResponsive(
      widget: coreOrderViewBill(
        widthScreen,
        context,
        maxWidthScreen,
      ),
      widthScreen: MediaQuery.of(context).size.width,
      isCoreLayout: false,
    );
    // return coreOrderViewBill(widthScreen, context);
  }

  Container coreOrderViewBill(
    double widthScreen,
    BuildContext context,
    double maxWidthScreen,
  ) {
    return Container(
      width: (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
      child: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                // color: Colors.blue,
                width: widthScreen * 0.1,
                child: Align(
                  alignment: Alignment.topCenter,
                  // child: Text(
                  //   "${widget.billDetail.quantity}",
                  //   style: textStyleMenuList(context),
                  // ),
                  child: defaultText(
                    context,
                    "${widget.billDetail.quantity}",
                    style: textStyleMenuList(context),
                  ),
                ),
              ),
              Container(
                // color: Colors.red,
                width: widthScreen * 0.78,
                child: Column(
                  children: [
                    Align(
                      alignment: Alignment.topLeft,
                      // child: Text(
                      //   widget.billDetail.menuName,
                      //   style: textStyleMenuList(context),
                      // ),
                      child: defaultText(
                        context,
                        widget.billDetail.menuName,
                        style: textStyleMenuList(context),
                      ),
                    ),
                    if (widget.billDetail.variant.isNotEmpty)
                      Align(
                          alignment: Alignment.topLeft,
                          // child: Text(
                          //   "Variants: ",
                          //   maxLines: 1,
                          //   overflow: TextOverflow.ellipsis,
                          //   // style: TextStyle(
                          //   //   fontWeight: FontWeight.w500,
                          //   //   fontSize: 12,
                          //   //   color: Colors.grey,
                          //   // ),
                          //   style: textStyleNormalFont(
                          //     context,
                          //     color: Colors.grey,
                          //     font: variantModalFont,
                          //   ),
                          // ),
                          child: defaultText(
                            context,
                            "Variants: ",
                            maxLines: 1,
                            overFlow: TextOverflow.ellipsis,
                            style: textStyleNormalFont(
                              context,
                              color: Colors.grey,
                              font: variantModalFont,
                            ),
                          )),
                    for (var x in widget.billDetail.variant)
                      Align(
                          alignment: Alignment.topLeft,
                          // child: Text(
                          //   " - ${x.toString()}",
                          //   maxLines: 1,
                          //   overflow: TextOverflow.ellipsis,
                          //   // style: const TextStyle(
                          //   //   fontWeight: FontWeight.w500,
                          //   //   fontSize: 12,
                          //   //   color: Colors.grey,
                          //   // ),
                          //   style: textStyleNormalFont(
                          //     context,
                          //     color: Colors.grey,
                          //     font: variantModalFont,
                          //   ),
                          // ),
                          child: defaultText(
                            context,
                            " - ${x.toString()}",
                            maxLines: 1,
                            overFlow: TextOverflow.ellipsis,
                            style: textStyleNormalFont(
                              context,
                              color: Colors.grey,
                              font: variantModalFont,
                            ),
                          )),
                    (widget.billDetail.notes != '')
                        ? Container(
                            padding: EdgeInsets.only(
                              left: widthScreen * 0.01,
                            ),
                            child: Align(
                                alignment: Alignment.topLeft,
                                // child: Text(
                                //   "Catatan: ${widget.billDetail.notes}",
                                //   // maxLines: 2,
                                //   // overflow: TextOverflow.ellipsis,
                                //   // style: const TextStyle(
                                //   //   fontWeight: FontWeight.w500,
                                //   //   fontSize: 12,
                                //   //   color: Colors.grey,
                                //   //   fontStyle: FontStyle.italic,
                                //   // ),
                                //   style: textStyleNormalFont(
                                //     context,
                                //     color: Colors.grey,
                                //     font: variantModalFont,
                                //     fontStyle: FontStyle.italic,
                                //   ),
                                // ),
                                child: defaultText(
                                  context,
                                  "Catatan: ${widget.billDetail.notes}",
                                  style: textStyleNormalFont(
                                    context,
                                    color: Colors.grey,
                                    font: variantModalFont,
                                    fontStyle: FontStyle.italic,
                                  ),
                                )),
                          )
                        : const SizedBox(),
                    SizedBox(
                      height: MediaQuery.of(context).size.height * 0.01,
                    ),
                    Row(
                      children: [
                        Container(
                          width: widthScreen * 0.43,
                          // color: Colors.red,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              defaultText(
                                context,
                                formatNumber().format(
                                    amountParseToInt(widget.billDetail.total)),
                                style: textStyleMenuList(
                                  context,
                                  font: normalFont,
                                ),
                              ),
                              // Text(
                              //   formatNumber().format(
                              //       amountParseToInt(widget.billDetail.total)),
                              //   // style: const TextStyle(
                              //   //     fontWeight: FontWeight.w600, fontSize: 20),
                              //   style: textStyleMenuList(
                              //     context,
                              //     font: normalFont,
                              //   ),
                              // ),
                              (widget.tableMode == multiTable ||
                                      widget.tableMode == singleTable)
                                  ?
                                  // Text(
                                  //     // (widget.billDetail.orderStatus == completeOrder)
                                  //     //     ? 'Complete'
                                  //     //     : (widget.billDetail.orderStatus ==
                                  //     //             cancelOrder)
                                  //     //         ? 'Canceled'
                                  //     //         : (widget.billDetail.orderStatus ==
                                  //     //                 pendingOrder)
                                  //     //             ? 'Pending'
                                  //     //             : 'Preparing',
                                  //     getOrderStatus(
                                  //         widget.billDetail.orderStatus),
                                  //     textAlign: TextAlign.end,
                                  //     // style: TextStyle(
                                  //     //   fontWeight: FontWeight.w500,
                                  //     //   fontSize: 15,
                                  //     //   color: (widget.billDetail.orderStatus ==
                                  //     //           completeOrder)
                                  //     //       ? successColor
                                  //     //       : (widget.billDetail.orderStatus ==
                                  //     //               cancelOrder)
                                  //     //           ? cancelColor
                                  //     //           : (widget.billDetail.orderStatus ==
                                  //     //                   processingOrder)
                                  //     //               ? processingColor
                                  //     //               : pendingColor,
                                  //     // ),
                                  //     style: textStyleNormalFont(
                                  //       context,
                                  //       color: (widget.billDetail.orderStatus ==
                                  //               completeOrder)
                                  //           ? successColor
                                  //           : (widget.billDetail.orderStatus ==
                                  //                   cancelOrder)
                                  //               ? cancelColor
                                  //               : (widget.billDetail
                                  //                           .orderStatus ==
                                  //                       processingOrder)
                                  //                   ? processingColor
                                  //                   : pendingColor,
                                  //       font: variantModalFont,
                                  //     ),
                                  //   )
                                  defaultText(
                                      context,
                                      getOrderStatus(
                                          widget.billDetail.orderStatus),
                                      textAlign: TextAlign.end,
                                      style: textStyleNormalFont(
                                        context,
                                        color: (widget.billDetail.orderStatus ==
                                                completeOrder)
                                            ? successColor
                                            : (widget.billDetail.orderStatus ==
                                                    cancelOrder)
                                                ? dangerColor
                                                : (widget.billDetail
                                                            .orderStatus ==
                                                        processingOrder)
                                                    ? processingColor
                                                    : pendingColor,
                                        font: variantModalFont,
                                      ),
                                    )
                                  : const SizedBox(),
                            ],
                          ),
                        ),
                        Container(
                          width: widthScreen * 0.35,
                          // color: Colors.blue,
                          // padding: EdgeInsets.only(
                          //     right: widthScreen * 0.01),
                          child: (widget.tableMode == singleTable &&
                                  widget.tableStatus == tableStatusOpen)
                              ? Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Container(
                                      // color: Colors.red,
                                      width: widthScreen * 0.1,
                                      child: Align(
                                        alignment: Alignment.center,
                                        child: noteMenu(
                                            context,
                                            widget.billDetail.notes,
                                            initialValue,
                                            fromBill,
                                            id: widget.billDetail.id),
                                      ),
                                    ),
                                    GestureDetector(
                                      onTap: () {
                                        if (initialValue > 1) {
                                          setState(() {
                                            initialValue -= 1;
                                            amount =
                                                initialValue * amountPeritem;
                                            isUserTapped = true;
                                          });
                                          // await Api.changeOrderDetail(
                                          //   context,
                                          //   widget.billDetail.id,
                                          //   initialValue,
                                          //   widget.billDetail.notes,
                                          // );
                                          changeOrderDetail(
                                              context,
                                              widget.billDetail.id,
                                              initialValue,
                                              widget.billDetail.notes);
                                        } else {
                                          deleteOrder(
                                              context,
                                              widget.billDetail.menuName,
                                              ontapOkDelete,
                                              ontapCancelDelete);
                                        }
                                      },
                                      child: Container(
                                        color: backgroundColor,
                                        width: widthScreen * 0.06,
                                        // child: Icon(Icons.remove_circle_outline,
                                        //     color: buttonColor),
                                        child: Align(
                                          alignment: Alignment.center,
                                          child: fontAwesome(
                                            context,
                                            minusCircle,
                                            minusCircleSize,
                                            color: buttonColor,
                                          ),
                                        ),
                                      ),
                                    ),
                                    Container(
                                        // color: Colors.green,
                                        width: widthScreen * 0.09,
                                        // child: Text(
                                        //   initialValue.toString(),
                                        //   textAlign: TextAlign.center,
                                        //   // style: TextStyle(
                                        //   //     fontWeight: FontWeight.w400,
                                        //   //     fontSize: MediaQuery.of(context)
                                        //   //             .size
                                        //   //             .height *
                                        //   //         0.02,
                                        //   //     color: Colors.grey),
                                        //   style: textStyleNormalFont(context),
                                        // ),
                                        child: Align(
                                          alignment: Alignment.center,
                                          child: defaultText(
                                            context,
                                            initialValue.toString(),
                                            textAlign: TextAlign.center,
                                            style: textStyleNormalFont(context),
                                          ),
                                        )),
                                    GestureDetector(
                                      onTap: () {
                                        setState(() {
                                          initialValue += 1;
                                          amount = initialValue * amountPeritem;
                                          isUserTapped = true;
                                        });
                                        // await Api.changeOrderDetail(
                                        //   context,
                                        //   widget.billDetail.id,
                                        //   initialValue,
                                        //   widget.billDetail.notes,
                                        // );
                                        changeOrderDetail(
                                            context,
                                            widget.billDetail.id,
                                            initialValue,
                                            widget.billDetail.notes);
                                      },
                                      child: Container(
                                        color: backgroundColor,
                                        width: widthScreen * 0.06,
                                        // child: Icon(
                                        //   Icons.add_circle_outline_rounded,
                                        //   color: buttonColor,
                                        // ),
                                        child: Align(
                                          alignment: Alignment.center,
                                          child: fontAwesome(
                                            context,
                                            plusCicle,
                                            plusCicleSize,
                                            color: buttonColor,
                                          ),
                                        ),
                                      ),
                                    )
                                  ],
                                )
                              : const SizedBox(),
                        ),
                      ],
                    )
                  ],
                ),
              )
            ],
          ),
          SizedBox(
            height: MediaQuery.of(context).size.height * 0.02,
          )
        ],
      ),
    );
  }

  // GestureDetector deleteOrderDetail(
  //     BuildContext context, String id, String menuName) {
  //   return GestureDetector(
  //     onTap: () {
  //       deleteOrder(context, menuName, ontapOkDelete, ontapCancelDelete);
  //     },
  //     child: Align(
  //         alignment: Alignment.topCenter,
  //         child: Icon(
  //           Icons.delete,
  //           color: cancelColor,
  //           size: MediaQuery.of(context).size.width * 0.05,
  //         )),
  //   );
  // }

  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,
    );
  }
}
