// ignore_for_file: sized_box_for_whitespace

import 'dart:convert';
import 'dart:math';

import 'package:byod/bloc/feedback_select.dart';
import 'package:byod/bloc/member_info.dart';
import 'package:byod/helper/helper.dart';
import 'package:byod/helper/widget/style.dart';
import 'package:byod/ui/history_order/history_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 'package:uuid/uuid.dart';

import '../../api/api.dart';
import '../../bloc/branch_exist.dart';
import '../../bloc/feedback_option.dart';
import '../../bloc/view_bill.dart';
import '../../bloc/voucher_list.dart';
import '../../helper/widget/button_dialog.dart';
import '../../helper/widget/emoticon_rate.dart';
import '../../helper/widget/emoticon_rate_new.dart';
import '../../helper/widget/open_url.dart';
import '../../helper/widget/thousand_formatter.dart';
import '../../main.dart';
import '../../models/bill.dart';
import '../../models/feedback_option.dart';
import '../../models/member_info.dart';
import '../../models/rate_value_selected.dart';
import '../build_version.dart';
import '../history_order/history.dart';
import '../home/new_home2.dart';
import '../payment/function.dart';
import '../payment/payment.dart';
import 'app_bar.dart';
import 'list_order.dart';
import 'rincian_pembayaran.dart';
import 'shimmer_bill.dart';

class ViewBillNew extends StatelessWidget {
  // const ViewBillNew({Key? key}) : super(key: key);

  final bool isHistory;
  final String sessionId;
  final String branchCodeH;
  final String brandCodeH;
  final String tableNumberH;
  final String token;
  final String userName;
  const ViewBillNew({
    Key? key,
    this.isHistory = false,
    this.sessionId = '',
    this.branchCodeH = '',
    this.brandCodeH = '',
    this.tableNumberH = '',
    this.token = '',
    this.userName = '',
  }) : super(key: key);

  // final RefreshController _refreshController =
  //     RefreshController(initialRefresh: false);

  void saveBillDetail(List<Bill> dataBill) async {
    await prefs.setString('total_order', dataBill[0].totalSeluruhOrderan);
    await prefs.setString('date_order', dataBill[0].dateOrder);
  }

  void getBillFunc(BuildContext context) {
    if (!isHistory) {
      context.read<ViewBillBloc>().getBill();
    } else {
      context.read<ViewBillBloc>().getBill(
            sessionIdH: sessionId,
            branchCodeH: branchCodeH,
            brandCodeH: brandCodeH,
            tableNumberH: tableNumberH,
            tokenH: token,
            userNameH: userName,
          );
    }
  }

  @override
  Widget build(BuildContext context) {
    context.read<FeedBackOptionBloc>().getOptionFeedback();
    context.read<ViewBillBloc>().backToDefault();
    getBillFunc(context);
    double widthScreen = responsiveWidthScreen(context);
    double maxWidthScreen = getMaxWidthScreen(context, useResponsive);
    double currentScreen = MediaQuery.of(context).size.width;

    //**UUID */
    const uuidInit = Uuid();
    var uuid = uuidInit.v4();
    //** UUID */
    String branchCode = prefs.getString("outlet") ?? '';
    String brandCode = prefs.getString("brand") ?? '';
    String tableNumber = prefs.getString("table_number") ?? '';
    String role = prefs.getString("role") ?? '';
    String customerName = prefs.getString("userName") ?? '';
    String cashierName = prefs.getString("cashier_name") ?? '';
    // String token = prefs.getString("token") ?? '';
    String sessionID = prefs.getString("sessionId") ?? uuid;
    int tableMode = prefs.getInt('table_mode') ?? defaultTable;
    List<String> historyOrder = prefs.getStringList('list_history') ?? [];

    return SafeArea(
      child: Scaffold(
        backgroundColor: backgroundColorViewBill,
        body: RefreshIndicator(
          color: buttonColor,
          backgroundColor: backgroundColor,
          onRefresh: () {
            return Future.delayed(
              const Duration(milliseconds: 1500),
              () {
                getBillFunc(context);
              },
            );
          },
          child: BlocBuilder<ViewBillBloc, List<Bill>>(
            builder: (ctxViewBill, dataBill) {
              if (dataBill.isNotEmpty) {
                if (dataBill[0].id == defaultViewBill) {
                  return ScreenResponsive(
                    // widget: waitingBill(
                    //   context,
                    //   widthScreen,
                    //   maxWidthScreen,
                    // ),
                    widget: ShimmerBill(
                      widthScreen: widthScreen,
                      maxWidthScreen: maxWidthScreen,
                      context: context,
                    ),
                    widthScreen: currentScreen,
                    isCoreLayout: true,
                  );
                } else {
                  saveBillDetail(dataBill);

                  // int totalService = 0;
                  // int totalServiceTax = 0;

                  // int individuTotalPayment = 0;
                  // int individuPaymentPaid = 0;
                  int outStandingIndividu = 0;

                  // int allPaymentPaid = 0;
                  int outStandingAll = 0;
                  int totalDiscount = 0;

                  // bool isIndividuHaveWaitingPayment = false;
                  // String paymentToRedirect = '';
                  // String paymentId = '';

                  // check payment pending ketika table di lock backend
                  // bool isStillHavePaymentPending = false;

                  if (dataBill.isNotEmpty) {
                    // int indexWherePendingPayment = dataBill[0]
                    //     .paymentList
                    //     .indexWhere((element) => element.isApproved == false);
                    // if (indexWherePendingPayment != -1) {
                    //   isStillHavePaymentPending = true;
                    // }

                    //service and servicetax
                    // totalService = amountParseToInt(dataBill[0].totalService);
                    // totalServiceTax =
                    //     amountParseToInt(dataBill[0].totalServiceTax);

                    // for (var x in dataBill) {
                    //   if (x.customerName == customerName) {
                    //     // individuTotalPayment = x.totalPerCustomer;
                    //   }

                    //   //service and tax
                    //   // for (var bd in x.billDetail) {
                    //   //   totalService += amountParseToInt(bd.service);
                    //   //   totalServiceTax += amountParseToInt(bd.serviceTax);
                    //   // }
                    // }
                    // if (dataBill[0].paymentList.isNotEmpty) {
                    //   for (var p in dataBill[0].paymentList) {
                    //     // if (p.isApproved && p.customerNamePay == customerName) {
                    //     //   individuPaymentPaid += amountParseToInt(p.amount);
                    //     // }
                    //     if (p.isApproved) {
                    //       allPaymentPaid += amountParseToInt(p.amount);
                    //     }
                    //     if (!p.isApproved) {
                    //       if (p.paymentUrl != '' &&
                    //           p.customerNamePay == customerName) {
                    //         isIndividuHaveWaitingPayment = true;
                    //         paymentToRedirect = p.paymentUrl;
                    //         paymentId = p.id;
                    //       }
                    //     }
                    //   }
                    // }
                    outStandingAll =
                        amountParseToInt(dataBill[0].outStandingPay);
                    totalDiscount = amountParseToInt(dataBill[0].discountTotal);
                    outStandingIndividu =
                        amountParseToInt(dataBill[0].outStandingIndividu);
                  }

                  void ontapOkAfterCashier() async {
                    Api.addPayment(
                      context,
                      dataBill[0].id,
                      branchCode,
                      brandCode,
                      customerName,
                      payCash,
                      fullPayment,
                      '',
                      outStandingAll,
                    ).then((value) {
                      if (value == 'OK') {
                        ratingModal(
                          context,
                          dataBill,
                          isHistory,
                          sessionID: sessionId,
                        );
                      }
                    });
                    Navigator.pop(context);
                    // Navigator.push(context,
                    //     MaterialPageRoute(builder: (_) => FinishOrder()));
                  }

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

                  void onTapCashier() {
                    String title;
                    String description;
                    String textOnOk = 'OK';
                    String textOnCancel = 'Batal';
                    // if (outStandingAll > 0) {
                    // Navigator.pop(context);
                    title = 'Tutup Pesanan';
                    description = '''
Selesaikan transaksi dan tutup pesanan ?

Mohon menuju kasir untuk meminta bukti pembayaran''';
                    // } else {
                    //   // // Navigator.pop(context);
                    //   // EasyLoading.showInfo('Tidak ada tagihan yang perlu dibayar');
                    //   title = 'Tutup Pesanan & Minta Bill';
                    //   description =
                    //       'Transaksi akan ditutup dan silakan meminta bill di kasir';
                    // }

                    buttonDialogGlobal(
                      context,
                      title,
                      description,
                      textOnOk,
                      textOnCancel,
                      ontapOkAfterCashier,
                      ontapCancelAfterCashier,
                      okButtonColor: buttonColor,
                      cancelButtonColor: cancelColorButton,
                    );
                  }

                  return ScreenResponsive(
                    widget: CoreBill(
                      widthScreen: widthScreen,
                      dataBill: dataBill,
                      outStandingAll: outStandingAll,
                      totalDiscount: totalDiscount,
                      isHistory: isHistory,
                      customerName: customerName,
                      outStandingIndividu: outStandingIndividu,
                      tableMode: tableMode,
                      onTapCashier: onTapCashier,
                      branchCode: branchCode,
                      brandCode: brandCode,
                      sessionId: sessionId,
                    ),
                    widthScreen: MediaQuery.of(context).size.width,
                    isCoreLayout: true,
                  );
                }
              } else {
                return ScreenResponsive(
                  widget: EmptyBill(
                    widthScreen: widthScreen,
                    branchCode: branchCode,
                    brandCode: brandCode,
                    customerName: customerName,
                    isHistory: isHistory,
                    sessionId: sessionID,
                    historyOrder: historyOrder,
                  ),
                  widthScreen: currentScreen,
                  isCoreLayout: true,
                );
              }
            },
          ),
        ),
      ),
    );
  }

  // Future<dynamic> ratingModal(
  //     BuildContext context, List<Bill> dataBill, bool isHistory,
  //     {String sessionID = ''}) {
  //   return showDialog(
  //     context: context,
  //     builder: (BuildContext context) => AlertDialog(
  //       title: defaultText(
  //         context,
  //         'Bagaimana pengalaman anda bertransaksi di excelso ?',
  //         style: textStyleNormalFont(context),
  //       ),
  //       content: EmoticonRate(
  //         bill: dataBill[0],
  //         isHistory: isHistory,
  //         sessionId: sessionID,
  //       ),
  //     ),
  //   );
  // }
}

class CoreBill extends StatelessWidget {
  const CoreBill({
    Key? key,
    required this.widthScreen,
    required this.dataBill,
    required this.outStandingAll,
    required this.totalDiscount,
    required this.isHistory,
    required this.customerName,
    required this.outStandingIndividu,
    required this.tableMode,
    required this.onTapCashier,
    required this.branchCode,
    required this.brandCode,
    required this.sessionId,
  }) : super(key: key);

  final double widthScreen;
  final List<Bill> dataBill;
  final int outStandingAll;
  final int totalDiscount;
  final bool isHistory;
  final String customerName;
  final int outStandingIndividu;
  final int tableMode;
  final void Function() onTapCashier;
  final String branchCode;
  final String brandCode;
  final String sessionId;

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<MemberInfoBloc, MemberInfo>(
      builder: (contextMember, memberinfo) {
        return Container(
          width: widthScreen,
          // padding: const EdgeInsets.symmetric(horizontal: paddingLeftRight),
          child: Stack(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  CustomAppBar(
                    isHistory: isHistory,
                  ),
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            width: double.infinity,
                            color: backgroundWhite,
                            padding: const EdgeInsets.symmetric(
                                horizontal: paddingLeftRight),
                            child: defaultText(
                                context, 'Meja ${dataBill[0].tableName}',
                                style: viewbillStyle()),
                          ),
                          Container(
                            width: double.infinity,
                            color: backgroundWhite,
                            padding: const EdgeInsets.only(
                              left: paddingLeftRight,
                              right: paddingLeftRight,
                              bottom: 18,
                            ),
                            child: defaultText(
                                context, dataBill[0].customerName,
                                style: customerNameViewbill()),
                          ),
                          // const Divider(
                          //   color: backgroundColorViewBill,
                          //   thickness: 24,
                          // ),
                          const SizedBox(
                            height: 24,
                          ),
                          (dataBill[0].isFeedBack == false &&
                                  dataBill[0].tableStatus != tableStatusOpen)
                              ? Column(
                                  children: [
                                    GestureDetector(
                                      onTap: () {
                                        ratingModal(
                                            context, dataBill, isHistory);
                                      },
                                      child: Container(
                                        height: 197,
                                        width: double.infinity,
                                        color: backgroundWhite,
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          children: [
                                            defaultText(
                                              context,
                                              'Berikan Rating',
                                              style: emojiStyle(),
                                            ),
                                            const SizedBox(
                                              height: 15,
                                            ),
                                            defaultText(
                                              context,
                                              'Bagaimana pengalaman anda bertransaksi di excelso',
                                              style: emojiStyle(),
                                            ),
                                            const SizedBox(
                                              height: 19,
                                            ),
                                            Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.center,
                                              children: const [
                                                Image(
                                                  width: 76,
                                                  height: 76,
                                                  image: AssetImage(
                                                      'assets/emoji/bad_grey.png'),
                                                ),
                                                SizedBox(
                                                  width: 28,
                                                ),
                                                Image(
                                                  width: 76,
                                                  height: 76,
                                                  image: AssetImage(
                                                      'assets/emoji/neutral_grey.png'),
                                                ),
                                                SizedBox(
                                                  width: 28,
                                                ),
                                                Image(
                                                  width: 76,
                                                  height: 76,
                                                  image: AssetImage(
                                                      'assets/emoji/good_grey.png'),
                                                )
                                              ],
                                            )
                                          ],
                                        ),
                                      ),
                                    ),
                                    const SizedBox(
                                      height: 24,
                                    ),
                                  ],
                                )
                              : const SizedBox(),
                          Container(
                            width: double.infinity,
                            color: backgroundWhite,
                            padding: const EdgeInsets.only(
                              left: paddingLeftRight,
                              right: paddingLeftRight,
                              top: 16,
                            ),
                            child: defaultText(
                              context,
                              'Daftar Order',
                              style: viewbillStyle(
                                font: 14,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                          ListOrder(
                            billDetail: dataBill[0].billDetail,
                            isHistory: isHistory,
                            tableStatus: dataBill[0].tableStatus,
                          ),
                          const SizedBox(
                            height: 24,
                          ),
                          const AddMoreOrder(),
                          const Divider(
                            color: backgroundColorViewBill,
                            thickness: 24,
                          ),
                          RincianPembayaran(
                            dataBill: dataBill,
                            totalDiscount: totalDiscount,
                            outStandingAll: outStandingAll,
                          ),
                          (dataBill[0].paymentList.isNotEmpty)
                              ? Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    const SizedBox(
                                      height: 24,
                                    ),
                                    Container(
                                      width: widthScreen,
                                      color: backgroundWhite,
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Container(
                                            padding: const EdgeInsets.only(
                                              left: paddingLeftRight,
                                              right: paddingLeftRight,
                                              top: 16,
                                              bottom: 20,
                                            ),
                                            child: defaultText(
                                              context,
                                              'Payment List',
                                              style: viewbillStyle(
                                                font: 14,
                                              ),
                                            ),
                                          ),
                                          Container(
                                            padding: const EdgeInsets.only(
                                              left: paddingLeftRight,
                                              right: paddingLeftRight,
                                              bottom: 12,
                                            ),
                                            child: const Divider(
                                              thickness: 0.3,
                                              color: dividerGrey,
                                            ),
                                          ),
                                          Container(
                                            padding: const EdgeInsets.only(
                                              left: paddingLeftRight,
                                              right: paddingLeftRight,
                                            ),
                                            child: Column(
                                              mainAxisSize: MainAxisSize.min,
                                              children: [
                                                for (int i = 0;
                                                    i <
                                                        dataBill[0]
                                                            .paymentList
                                                            .length;
                                                    i++)
                                                  Column(
                                                    children: [
                                                      GestureDetector(
                                                        onTap: () async {
                                                          // hanya payment yang belum approve, method doku only dan payment url tidak string kosong
                                                          if (dataBill[0]
                                                                      .paymentList[
                                                                          i]
                                                                      .method ==
                                                                  payCard &&
                                                              dataBill[0]
                                                                      .paymentList[
                                                                          i]
                                                                      .paymentUrl !=
                                                                  '' &&
                                                              dataBill[0]
                                                                      .paymentList[
                                                                          i]
                                                                      .isApproved ==
                                                                  false) {
                                                            await EasyLoading
                                                                .show(
                                                              status:
                                                                  'Harap tunggu...',
                                                              maskType:
                                                                  EasyLoadingMaskType
                                                                      .none,
                                                            );
                                                            await EasyLoading
                                                                .dismiss();
                                                            htmlOpenLink(dataBill[
                                                                    0]
                                                                .paymentList[i]
                                                                .paymentUrl);
                                                          }
                                                        },
                                                        child: Container(
                                                          height: 72,
                                                          padding:
                                                              const EdgeInsets
                                                                  .all(16),
                                                          decoration:
                                                              BoxDecoration(
                                                            borderRadius:
                                                                BorderRadius
                                                                    .circular(
                                                                        9),
                                                            color:
                                                                backgroundWhite,
                                                            boxShadow: const [
                                                              BoxShadow(
                                                                color:
                                                                    Colors.grey,
                                                                blurRadius: 5.0,
                                                              )
                                                            ],
                                                          ),
                                                          child: Row(
                                                            children: [
                                                              Expanded(
                                                                child:
                                                                    Container(
                                                                  height: double
                                                                      .infinity,
                                                                  child: Column(
                                                                    crossAxisAlignment:
                                                                        CrossAxisAlignment
                                                                            .start,
                                                                    mainAxisAlignment:
                                                                        MainAxisAlignment
                                                                            .spaceEvenly,
                                                                    children: [
                                                                      defaultText(
                                                                        context,
                                                                        dataBill[0]
                                                                            .paymentList[i]
                                                                            .customerNamePay,
                                                                        maxLines:
                                                                            1,
                                                                        overFlow:
                                                                            TextOverflow.ellipsis,
                                                                        style:
                                                                            viewbillStyle(
                                                                          font:
                                                                              12,
                                                                        ),
                                                                      ),
                                                                      defaultText(
                                                                        context,
                                                                        dataBill[0]
                                                                            .paymentList[i]
                                                                            .name,
                                                                        maxLines:
                                                                            1,
                                                                        overFlow:
                                                                            TextOverflow.ellipsis,
                                                                        style:
                                                                            viewbillStyle(
                                                                          font:
                                                                              12,
                                                                          color:
                                                                              textGreyBill,
                                                                        ),
                                                                      ),
                                                                    ],
                                                                  ),
                                                                ),
                                                              ),
                                                              Container(
                                                                width: 110,
                                                                height: double
                                                                    .infinity,
                                                                child: Column(
                                                                  crossAxisAlignment:
                                                                      CrossAxisAlignment
                                                                          .end,
                                                                  mainAxisAlignment:
                                                                      MainAxisAlignment
                                                                          .spaceEvenly,
                                                                  children: [
                                                                    defaultText(
                                                                      context,
                                                                      "Rp ${formatNumber().format(amountParseToInt(dataBill[0].paymentList[i].amount))}",
                                                                      maxLines:
                                                                          1,
                                                                      overFlow:
                                                                          TextOverflow
                                                                              .ellipsis,
                                                                      style:
                                                                          viewbillStyle(
                                                                        font:
                                                                            12,
                                                                      ),
                                                                    ),
                                                                    defaultText(
                                                                      context,
                                                                      getpaymentStatus(
                                                                        dataBill[0]
                                                                            .paymentList[i]
                                                                            .isApproved,
                                                                        dataBill[0]
                                                                            .paymentList[i]
                                                                            .method,
                                                                      ),
                                                                      maxLines:
                                                                          1,
                                                                      overFlow:
                                                                          TextOverflow
                                                                              .ellipsis,
                                                                      style:
                                                                          viewbillStyle(
                                                                        font:
                                                                            12,
                                                                        color:
                                                                            getPaymentStatusColor(
                                                                          dataBill[0]
                                                                              .paymentList[i]
                                                                              .isApproved,
                                                                        ),
                                                                      ),
                                                                    ),
                                                                  ],
                                                                ),
                                                              )
                                                            ],
                                                          ),
                                                        ),
                                                      ),
                                                      const SizedBox(
                                                        height: 5,
                                                      )
                                                    ],
                                                  ),
                                              ],
                                            ),
                                            // child: ListView.builder(
                                            //   itemCount: 3,
                                            //   itemBuilder: (ctxPayment, i) {
                                            //     return Container(
                                            //       height: 72,
                                            //       decoration: BoxDecoration(
                                            //         borderRadius:
                                            //             BorderRadius.circular(
                                            //                 9),
                                            //         color: backgroundWhite,
                                            //         boxShadow: const [
                                            //           BoxShadow(
                                            //             color: Colors.grey,
                                            //             blurRadius: 10.0,
                                            //           )
                                            //         ],
                                            //       ),
                                            //     );
                                            //   },
                                            // ),
                                          )
                                        ],
                                      ),
                                    )
                                  ],
                                )
                              : const SizedBox(),
                          Container(
                            padding: const EdgeInsets.only(top: 5, bottom: 5),
                            color: backgroundWhite,
                            width: double.infinity,
                            child: Align(
                              alignment: Alignment.center,
                              child: defaultText(
                                context,
                                "Harga sudah termasuk pajak",
                                style: rincianPembayaran(
                                  fontStyle: FontStyle.italic,
                                ),
                              ),
                            ),
                          ),
                          SizedBox(
                            height: (dataBill[0].tableStatus == tableStatusOpen)
                                ? 180
                                : 120,
                          )
                        ],
                      ),
                    ),
                  )
                ],
              ),
              Positioned(
                bottom: 0,
                child: Container(
                  decoration: const BoxDecoration(
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(16),
                      topRight: Radius.circular(16),
                    ),
                    color: backgroundWhite,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey,
                        blurRadius: 10.0,
                      )
                    ],
                  ),
                  padding: const EdgeInsets.symmetric(
                      horizontal: paddingLeftRight, vertical: paddingLeftRight),
                  width: widthScreen,
                  child: Column(
                    children: [
                      GestureDetector(
                        onTap: () {
                          if (dataBill[0].tableStatus == tableStatusOpen) {
                            if (tableMode == singleTable &&
                                memberinfo.id == '') {
                              addPayment(
                                context,
                                dataBill[0].id,
                                branchCode,
                                brandCode,
                                customerName,
                                payCard,
                                fullPayment,
                                '',
                                outStandingAll,
                              );
                            } else {
                              buttonDialogAllPayment(
                                context,
                                dataBill,
                                customerName,
                                outStandingIndividu,
                                outStandingAll,
                                tableMode,
                                onTapCashier,
                                widthScreen,
                                memberinfo,
                                branchCode,
                                brandCode,
                              );
                            }
                          }
                        },
                        child: Container(
                          margin: const EdgeInsets.only(top: 12),
                          height: 43,
                          width: double.infinity,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(33),
                            color: (dataBill[0].tableStatus == tableStatusOpen)
                                ? buttonColor
                                : disabledColor,
                          ),
                          child: Center(
                            child: defaultText(
                              context,
                              (dataBill[0].tableStatus == tableStatusOpen)
                                  ? 'Pembayaran Online'
                                  : 'Transaksi Selesai',
                              style: buttonBottomBill(),
                            ),
                          ),
                        ),
                      ),
                      (dataBill[0].isFeedBack == false &&
                              dataBill[0].tableStatus == tableStatusOpen)
                          ? GestureDetector(
                              onTap: () {
                                if (dataBill[0].tableStatus ==
                                    tableStatusOpen) {
                                  onTapCashier();
                                } else {
                                  if (dataBill[0].isFeedBack == false) {
                                    ratingModal(
                                      context,
                                      dataBill,
                                      isHistory,
                                      sessionID: sessionId,
                                    );
                                  }
                                }
                              },
                              child: Container(
                                margin: const EdgeInsets.only(top: 12),
                                height: 43,
                                width: double.infinity,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(33),
                                  color: successColor,
                                ),
                                child: Center(
                                  child: defaultText(
                                    context,
                                    (dataBill[0].tableStatus == tableStatusOpen)
                                        ? 'Tutup Pesanan & Minta Bill'
                                        : 'Beri Penilaian',
                                    style: buttonBottomBill(),
                                  ),
                                ),
                              ),
                            )
                          : const SizedBox(),
                      const SizedBox(
                        height: 5,
                      ),
                      const BuildVersion()
                    ],
                  ),
                ),
              )
            ],
          ),
        );
      },
    );
  }
}

class EmptyBill extends StatelessWidget {
  EmptyBill({
    Key? key,
    required this.widthScreen,
    required this.isHistory,
    required this.customerName,
    required this.branchCode,
    required this.brandCode,
    required this.sessionId,
    required this.historyOrder,
  }) : super(key: key);

  final double widthScreen;
  final bool isHistory;
  final String customerName;
  final String branchCode;
  final String brandCode;
  final String sessionId;
  final String tableNumber = prefs.getString("table_number") ?? '';
  final List<String> historyOrder;

  final String role = prefs.getString('role') ?? '';
  final String cashierName = prefs.getString('cashier_name') ?? '';
  final String sessionID = prefs.getString('sessionId') ?? '';
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<MemberInfoBloc, MemberInfo>(
      builder: (contextMember, memberinfo) {
        return Container(
          width: widthScreen,
          // padding: const EdgeInsets.symmetric(horizontal: paddingLeftRight),
          child: Stack(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  CustomAppBar(
                    isHistory: isHistory,
                  ),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                            width: double.infinity,
                            color: backgroundWhite,
                            padding: const EdgeInsets.symmetric(
                                horizontal: paddingLeftRight),
                            child: defaultText(context, 'Meja $tableNumber',
                                style: viewbillStyle())),
                        Container(
                          width: double.infinity,
                          color: backgroundWhite,
                          padding: const EdgeInsets.only(
                            left: paddingLeftRight,
                            right: paddingLeftRight,
                            bottom: 18,
                          ),
                          child: defaultText(context, customerName,
                              style: customerNameViewbill()),
                        ),
                        const SizedBox(
                          height: 24,
                        ),
                        Expanded(
                          child: Container(
                            width: double.infinity,
                            color: backgroundWhite,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Container(
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: paddingLeftRight),
                                  child: Center(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        const Image(
                                          width: 187,
                                          height: 173,
                                          image: AssetImage(
                                              'assets/icons/big-cart.png'),
                                        ),
                                        const SizedBox(
                                          height: 24,
                                        ),
                                        defaultText(
                                          context,
                                          'Belum Ada Orderan',
                                          style: rincianPembayaran(
                                            font: 16,
                                            fontWeight: FontWeight.w700,
                                            color: backgroundColorViewBill,
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                ),
                                const SizedBox(
                                  height: 21,
                                ),
                                GestureDetector(
                                  onTap: () {
                                    context.read<BranchExist>().branchExist(
                                          branchCode,
                                          brandCode,
                                          role,
                                          cashierName,
                                          sessionID,
                                        );
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (_) => const NewHome2()));
                                  },
                                  child: Container(
                                    margin: const EdgeInsets.symmetric(
                                      horizontal: paddingLeftRight,
                                    ),
                                    height: 43,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(8),
                                      color: buttonColor,
                                    ),
                                    child: Center(
                                      child: defaultText(
                                        context,
                                        'Buat Pesanan Baru',
                                        style: addButton(
                                          font: 14,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                                const SizedBox(
                                  height: 12,
                                ),
                                GestureDetector(
                                  onTap: () {
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (_) => HistoryOrderNew(
                                          historyOrder: historyOrder,
                                        ),
                                      ),
                                    );
                                  },
                                  child: Container(
                                    margin: const EdgeInsets.symmetric(
                                      horizontal: paddingLeftRight,
                                    ),
                                    height: 43,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(8),
                                      color: buttonColor,
                                    ),
                                    child: Center(
                                      child: defaultText(
                                        context,
                                        'Lihat Transaksi Terakhir',
                                        style: addButton(
                                          font: 14,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  )
                ],
              ),
              Positioned(
                bottom: 0,
                child: Container(
                  padding: const EdgeInsets.symmetric(
                      horizontal: paddingLeftRight, vertical: paddingLeftRight),
                  width: widthScreen,
                  child: Column(
                    children: const [
                      SizedBox(
                        height: 5,
                      ),
                      BuildVersion()
                    ],
                  ),
                ),
              )
            ],
          ),
        );
      },
    );
  }
}

Future<dynamic> ratingModal(
    BuildContext context, List<Bill> dataBill, bool isHistory,
    {String sessionID = ''}) {
  double sizeImage = 76;
  final rateNote = TextEditingController();
  return showDialog(
    context: context,
    builder: (BuildContext context) => AlertDialog(
      content: EmoticonRateNew(
        sizeImage: sizeImage,
        rateNote: rateNote,
        isHistory: isHistory,
        dataBill: dataBill,
        sessionID: sessionID,
      ),
    ),
  );
}

Future<dynamic> buttonDialog(BuildContext context, List<Bill> dataBill,
    int outStandingAll, double widthScreen) {
  final nominalController = TextEditingController();

  return showDialog(
      context: context,
      builder: (BuildContext context) => AlertDialog(
            title: defaultText(context, "Nominal Bayar"),
            content: SizedBox(
              height: MediaQuery.of(context).size.height * 0.3,
              width: widthScreen * widhtDialog,
              child: Column(
                children: [
                  Container(
                    height: MediaQuery.of(context).size.height * 0.12,
                    child: Column(
                      children: [
                        TextField(
                          // autofocus: true,
                          keyboardType: TextInputType.number,
                          controller: nominalController,
                          inputFormatters: [ThousandsSeparatorInputFormatter()],
                          onChanged: (inputValue) {
                            var replaceComma =
                                inputValue.replaceAll(separatorThousand, '');
                            var inputAmount = int.tryParse(replaceComma);
                            if (inputAmount == null) {
                              EasyLoading.showToast(
                                  'Nominal hanya diisi dengan angka');
                            }
                          },

                          style: textStyleNormalFont(context),
                        ),
                        Align(
                          alignment: Alignment.topLeft,
                          child: defaultText(
                            context,
                            "Min ${formatNumber().format(amountParseToInt(dataBill[0].dokuMinPay))} - Max ${formatNumber().format(outStandingAll)}",
                          ),
                        )
                      ],
                    ),
                  ),
                  SizedBox(height: MediaQuery.of(context).size.height * 0.01),
                  GestureDetector(
                    onTap: () {
                      if (nominalController.text != '') {
                        var replaceComma = nominalController.text
                            .replaceAll(separatorThousand, '');
                        var inputAmount = int.tryParse(replaceComma);
                        if (nominalController.text == '') {
                          EasyLoading.showToast('Nominal wajib diisi');
                        } else if (inputAmount == null) {
                          EasyLoading.showToast(
                              'Nominal hanya diisi dengan angka');
                        } else if (inputAmount <
                            amountParseToInt(dataBill[0].dokuMinPay)) {
                          EasyLoading.showToast(
                              'Minimal bayar ${formatNumber().format(amountParseToInt(dataBill[0].dokuMinPay))}');
                        } else if (inputAmount > outStandingAll) {
                          EasyLoading.showToast(
                              'Maksimal bayar ${formatNumber().format(outStandingAll)}');
                        } else {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (_) => Payment(
                                  dataBill: dataBill,
                                  isIndividu: true,
                                  outstandingIndividu: inputAmount,
                                  outstandingAll: outStandingAll,
                                  title: ''),
                            ),
                          );
                        }
                      }
                    },
                    child: Container(
                      height: MediaQuery.of(context).size.height * heightTombol,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(roundedButton),
                          color: buttonColor),
                      child: Align(
                        child: defaultText(
                          context,
                          "OK",
                          style:
                              textStyleNormalFont(context, color: textInButton),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: MediaQuery.of(context).size.height * 0.02,
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: Container(
                      height: MediaQuery.of(context).size.height * heightTombol,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(roundedButton),
                        color: cancelColorButton,
                      ),
                      child: Align(
                        child: Text(
                          "Batal",
                          style: textStyleNormalFont(
                            context,
                            color: textCancelColor,
                          ),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ));
}

Future<dynamic> buttonDialogAllPayment(
  BuildContext context,
  List<Bill> dataBill,
  String customerName,
  int outStandingIndividu,
  int outStandingAll,
  int tableMode,
  void Function() ontapCashier,
  double widthScreen,
  MemberInfo memberinfo,
  String branchCode,
  String brandCode,
) async {
  int indexDataIndividu =
      dataBill.indexWhere((data) => data.customerName == customerName);
  double heighContainer;
  if (tableMode == singleTable && memberinfo.id != '') {
    heighContainer = MediaQuery.of(context).size.height * 0.45;
  } else if ((tableMode == multiTable && memberinfo.id == '') ||
      tableMode == singleTable && memberinfo.id != '') {
    heighContainer = MediaQuery.of(context).size.height * 0.3;
  } else {
    heighContainer = MediaQuery.of(context).size.height * 0.25;
  }
  int outStandingTopayMember = 0;
  if (memberinfo.id != '') {
    outStandingTopayMember =
        min(outStandingAll, amountParseToIntCrm(memberinfo.balance));
  }
  return showDialog(
      context: context,
      builder: (BuildContext context) => AlertDialog(
            title: defaultText(context, "Pilih cara pembayaran"),
            content: SizedBox(
              height: heighContainer,
              width: widthScreen * widhtDialog,
              child: Column(
                children: [
                  Container(
                    // height: MediaQuery.of(context).size.height * 0.05,
                    child: Align(
                      alignment: Alignment.topLeft,
                      child: defaultText(
                        context,
                        "Pembayaran online menggunakan saldo eWallet atau Virtual Account",
                        style: textStyleNormalFont(context),
                      ),
                    ),
                  ),
                  SizedBox(height: MediaQuery.of(context).size.height * 0.012),
                  GestureDetector(
                    onTap: () {
                      String titlePayment;
                      String customerName = prefs.getString('userName') ?? '';
                      bool isIndividu;
                      if (tableMode == multiTable) {
                        isIndividu = true;
                        titlePayment = 'Semua Bill';
                      } else {
                        isIndividu = false;
                        titlePayment = customerName;
                      }
                      if (outStandingAll > 0) {
                        if (tableMode == singleTable) {
                          addPayment(
                            context,
                            dataBill[0].id,
                            branchCode,
                            brandCode,
                            customerName,
                            payCard,
                            fullPayment,
                            '',
                            outStandingAll,
                          );
                        } else {
                          Navigator.pop(context);
                          buttonDialog(
                              context, dataBill, outStandingAll, widthScreen);
                        }
                      } else {
                        EasyLoading.showToast('Semua Tagihan Sudah Dibayar');
                      }
                    },
                    child: Container(
                      // height: MediaQuery.of(context).size.height * 0.04,
                      height: MediaQuery.of(context).size.height * heightTombol,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(roundedButton),
                          color: buttonColor),
                      child: Align(
                        child: defaultText(
                          context,
                          (tableMode == multiTable)
                              ? "Bayar Sebagian"
                              : "Online - Rp ${formatNumber().format(outStandingAll)}",
                          style: textStyleNormalFont(
                            context,
                            color: textInButton,
                          ),
                        ),
                      ),
                    ),
                  ),
                  (tableMode == multiTable)
                      ? SizedBox(
                          height: MediaQuery.of(context).size.height * 0.02,
                        )
                      : const SizedBox(),
                  (tableMode == multiTable)
                      ? GestureDetector(
                          onTap: () {
                            if (outStandingAll > 0) {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (_) => Payment(
                                          dataBill: dataBill,
                                          isIndividu: false,
                                          outstandingIndividu:
                                              outStandingIndividu,
                                          outstandingAll: outStandingAll,
                                          title: '')));
                            } else {
                              EasyLoading.showToast(
                                  'Semua Tagihan Sudah Dibayar');
                            }
                          },
                          child: Container(
                            // height: MediaQuery.of(context).size.height * 0.04,
                            height: MediaQuery.of(context).size.height *
                                heightTombol,
                            decoration: BoxDecoration(
                                borderRadius:
                                    BorderRadius.circular(roundedButton),
                                color: buttonColor),
                            child: Align(
                              child: defaultText(
                                context,
                                "Bayar Seluruhnya - Rp ${formatNumber().format(outStandingAll)}",
                                style: textStyleNormalFont(
                                  context,
                                  color: textInButton,
                                ),
                              ),
                            ),
                          ),
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? SizedBox(
                          height: MediaQuery.of(context).size.height * 0.02,
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? Container(
                          // height: MediaQuery.of(context).size.height * 0.05,
                          child: Align(
                            alignment: Alignment.topLeft,
                            child: defaultText(
                              context,
                              "Pembayaran dengan saldo member excelso CRM",
                              style: textStyleNormalFont(context),
                            ),
                          ),
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? SizedBox(
                          height: MediaQuery.of(context).size.height * 0.01,
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? GestureDetector(
                          onTap: () {
                            if (outStandingAll > 0) {
                              if (outStandingTopayMember <= 0) {
                                EasyLoading.showToast(
                                    'Tidak ada tagihan / Tidak ada balance');
                              } else {
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (_) => Payment(
                                            dataBill: dataBill,
                                            isIndividu: true,
                                            outstandingIndividu:
                                                outStandingTopayMember, // karena hanya excelso untuk saat ini jadi overide outstandingindividu dulu
                                            outstandingAll: outStandingAll,
                                            title: 'Dengan Balance',
                                            isUsingBalance: true)));
                              }
                            } else {
                              EasyLoading.showToast(
                                  'Semua Tagihan Sudah Dibayar');
                            }
                          },
                          child: Container(
                            // height:
                            //     MediaQuery.of(context).size.height * 0.04,
                            height: MediaQuery.of(context).size.height *
                                heightTombol,
                            decoration: BoxDecoration(
                                borderRadius:
                                    BorderRadius.circular(roundedButton),
                                color: buttonColor),
                            child: Align(
                              child: defaultText(
                                context,
                                "Excelco CRM Balance - Rp ${formatNumber().format(outStandingTopayMember)} ",
                                style: textStyleNormalFont(
                                  context,
                                  color: textInButton,
                                ),
                              ),
                            ),
                          ),
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? SizedBox(
                          height: MediaQuery.of(context).size.height * 0.02,
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? Container(
                          // height: MediaQuery.of(context).size.height * 0.05,
                          child: Align(
                            alignment: Alignment.topLeft,
                            child: defaultText(
                              context,
                              "Pembayaran dengan e-Voucher CRM",
                              style: textStyleNormalFont(context),
                            ),
                          ),
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? SizedBox(
                          height: MediaQuery.of(context).size.height * 0.01,
                        )
                      : const SizedBox(),
                  (memberinfo.id != '')
                      ? GestureDetector(
                          onTap: () {
                            int indexVoucher = dataBill[0]
                                .paymentList
                                .indexWhere(
                                    (element) => element.method == payVoucher);
                            if (indexVoucher != -1) {
                              // check apakah sudah pernah melakukan pembayran voucher
                              EasyLoading.showToast(
                                  'Voucher telah digunakan pada orderan ini');
                            } else if (outStandingAll > 0) {
                              if (indexDataIndividu == -1) {
                                EasyLoading.showToast(
                                    'Kamu Belum Memiliki Orderan');
                              } else {
                                context
                                    .read<VoucherListBloc>()
                                    .getVoucherList();
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (_) => Payment(
                                              dataBill: dataBill,
                                              isIndividu: false,
                                              indexIndividu: indexDataIndividu,
                                              isVoucher: true,
                                              outstandingIndividu:
                                                  outStandingIndividu,
                                              outstandingAll: outStandingAll,
                                              title: 'Voucher',
                                            )));
                              }
                            } else {
                              EasyLoading.showToast('Tidak ada tagihan');
                            }
                          },
                          child: Container(
                            height: MediaQuery.of(context).size.height *
                                heightTombol,
                            decoration: BoxDecoration(
                                borderRadius:
                                    BorderRadius.circular(roundedButton),
                                color: buttonColor),
                            child: Align(
                              child: defaultText(
                                context,
                                "Excelco CRM Voucher",
                                style: textStyleNormalFont(
                                  context,
                                  color: textInButton,
                                ),
                              ),
                            ),
                          ),
                        )
                      : const SizedBox(),
                  Divider(
                    thickness: MediaQuery.of(context).size.height * 0.001,
                    color: Colors.grey,
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: Container(
                      height: MediaQuery.of(context).size.height * heightTombol,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(roundedButton),
                        color: cancelColorButton,
                      ),
                      child: Align(
                        child: defaultText(
                          context,
                          "Batal",
                          style: textStyleNormalFont(
                            context,
                            color: textCancelColor,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ));
}

class AddMoreOrder extends StatelessWidget {
  const AddMoreOrder({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 80,

      width: double.infinity,
      color: backgroundWhite,
      padding: const EdgeInsets.symmetric(horizontal: paddingLeftRight),
      // color: Colors.red,
      child: Row(
        children: [
          Expanded(
            child: Container(
              child: defaultText(
                context,
                'Apa anda masih ingin memesan ?',
                maxLines: 2,
                overFlow: TextOverflow.ellipsis,
                style: viewbillStyle(
                  font: 16,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ),
          const SizedBox(
            width: 19,
          ),
          GestureDetector(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (_) => const NewHome2(),
                ),
              );
            },
            child: Container(
              width: 98,
              height: 30,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(21),
                color: buttonColor,
              ),
              child: Center(
                child: defaultText(
                  context,
                  'Tambah',
                  style: addButton(
                    font: 8,
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
