// ignore_for_file: sized_box_for_whitespace

import 'package:byod/helper/helper.dart';
import 'package:byod/helper/widget/style.dart';
import 'package:byod/ui/screen_responsive.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.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 '../../helper/widget/button_dialog.dart';
import '../../helper/widget/emoticon_rate.dart';
import '../../main.dart';
import '../../models/bill.dart';
import '../../models/bill_detail.dart';
import '../build_version.dart';
import '../history_order/history.dart';
import '../home/new_home2.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 branchCode;
  final String brandCodeH;
  final String tableNumberH;
  final String token;
  final String userName;
  const ViewBillNew({
    Key? key,
    this.isHistory = false,
    this.sessionId = '',
    this.branchCode = '',
    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);
  }

  @override
  Widget build(BuildContext context) {
    context.read<FeedBackOptionBloc>().getOptionFeedback();
    context.read<ViewBillBloc>().backToDefault();
    if (!isHistory) {
      context.read<ViewBillBloc>().getBill();
    } else {
      context.read<ViewBillBloc>().getBill(
            sessionIdH: sessionId,
            branchCodeH: brandCodeH,
            brandCodeH: brandCodeH,
            tableNumberH: tableNumberH,
            tokenH: token,
            userNameH: userName,
          );
    }

    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: backgroundWhite,
        body: RefreshIndicator(
          color: buttonColor,
          backgroundColor: backgroundColor,
          onRefresh: () {
            return Future.delayed(
              const Duration(milliseconds: 1500),
              () {
                context.read<ViewBillBloc>().getBill();
              },
            );
          },
          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,
                    ),
                    widthScreen: MediaQuery.of(context).size.width,
                    isCoreLayout: true,
                  );
                }
              } else {
                return ScreenResponsive(
                  widget: emptyBill(
                    widthScreen,
                    maxWidthScreen,
                    historyOrder,
                    context,
                  ),
                  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,
        ),
      ),
    );
  }

  Container emptyBill(double widthScreen, double maxWidthScreen,
      List<String> historyOrder, BuildContext context) {
    String branchCode = prefs.getString('outlet') ?? '';
    String tableNumber = prefs.getString('table_number') ?? '';
    String brandCode = prefs.getString('brand') ?? '';
    String role = prefs.getString('role') ?? '';
    String cashierName = prefs.getString('cashier_name') ?? '';
    String sessionID = prefs.getString('sessionId') ?? '';
    return Container(
      padding:
          EdgeInsets.only(left: widthScreen * 0.01, right: widthScreen * 0.01),
      width: (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
      // color: Colors.red,
      child: SingleChildScrollView(
        child: Stack(
          children: [
            Column(
              children: [
                CustomAppBar(
                  isHistory: isHistory,
                ),
                SizedBox(
                  height: MediaQuery.of(context).size.height * 0.92,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // Icon(
                      //   Icons.assignment,
                      //   size: 80,
                      //   color: buttonColor,
                      // ),
                      fontAwesome(
                        context,
                        listPesanan,
                        listPesananSizeViewBill,
                        color: buttonColor,
                      ),
                      defaultText(
                        context,
                        "Belum Ada Orderan",
                        textAlign: TextAlign.center,
                        style: textStyleMenuList(context),
                      ),
                      (historyOrder.isNotEmpty)
                          ? Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                GestureDetector(
                                  onTap: () {
                                    context.read<BranchExist>().branchExist(
                                          branchCode,
                                          brandCode,
                                          role,
                                          cashierName,
                                          sessionID,
                                        );
                                    Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (_) => const NewHome2()));
                                  },
                                  child: Container(
                                    padding: EdgeInsets.symmetric(
                                      horizontal: widthScreen * 0.02,
                                      vertical:
                                          MediaQuery.of(context).size.height *
                                              0.01,
                                    ),
                                    margin: EdgeInsets.symmetric(
                                        vertical:
                                            MediaQuery.of(context).size.height *
                                                0.01),
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(
                                          roundedSmallButton),
                                      color: buttonColor,
                                    ),
                                    child: defaultText(
                                      context,
                                      'Buat Pesanan Baru',
                                      textAlign: TextAlign.center,
                                      maxLines: 2,
                                      style: textStyleTambahPesanan(context),
                                    ),
                                  ),
                                ),
                                (historyOrder.isNotEmpty)
                                    ? SizedBox(
                                        width: widthScreen * 0.01,
                                      )
                                    : const SizedBox(),
                                (historyOrder.isNotEmpty)
                                    ? GestureDetector(
                                        onTap: () {
                                          Navigator.push(
                                            context,
                                            MaterialPageRoute(
                                              builder: (_) => HistoryOrder(
                                                historyOrder: historyOrder,
                                              ),
                                            ),
                                          );
                                        },
                                        child: Container(
                                          padding: EdgeInsets.symmetric(
                                            horizontal: widthScreen * 0.02,
                                            vertical: MediaQuery.of(context)
                                                    .size
                                                    .height *
                                                0.01,
                                          ),
                                          margin: EdgeInsets.symmetric(
                                              vertical: MediaQuery.of(context)
                                                      .size
                                                      .height *
                                                  0.01),
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(
                                                roundedSmallButton),
                                            color: buttonColor,
                                          ),
                                          child: defaultText(
                                            context,
                                            'Lihat Transaksi Terakhir',
                                            textAlign: TextAlign.center,
                                            maxLines: 2,
                                            style:
                                                textStyleTambahPesanan(context),
                                          ),
                                        ),
                                      )
                                    : const SizedBox()
                              ],
                            )
                          : const SizedBox()
                    ],
                  ),
                )
              ],
            ),
            Positioned(
              bottom: 10,
              child: Container(
                width: widthScreen,
                child: const BuildVersion(),
              ),
            )
          ],
        ),
      ),
    );
  }
}

class CoreBill extends StatelessWidget {
  const CoreBill({
    Key? key,
    required this.widthScreen,
    required this.dataBill,
    required this.outStandingAll,
    required this.totalDiscount,
    required this.isHistory,
  }) : super(key: key);

  final double widthScreen;
  final List<Bill> dataBill;
  final int outStandingAll;
  final int totalDiscount;
  final bool isHistory;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widthScreen,
      // padding: const EdgeInsets.symmetric(horizontal: paddingLeftRight),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          CustomAppBar(
            isHistory: isHistory,
          ),
          Expanded(
              child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                    padding: const EdgeInsets.symmetric(
                        horizontal: paddingLeftRight),
                    child: defaultText(context, 'Meja ${dataBill[0].tableName}',
                        style: viewbillStyle())),
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: paddingLeftRight),
                  child: defaultText(context, dataBill[0].customerName,
                      style: customerNameViewbill()),
                ),
                const SizedBox(
                  height: 18,
                ),
                const Divider(
                  color: backgroundColorViewBill,
                  thickness: 24,
                ),
                const SizedBox(
                  height: 16,
                ),
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: paddingLeftRight),
                  child: defaultText(
                    context,
                    'Daftar Order',
                    style: viewbillStyle(
                      font: 14,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
                ListOrder(
                  billDetail: dataBill[0].billDetail,
                ),
                const SizedBox(
                  height: 11,
                ),
                const Divider(
                  color: backgroundColorViewBill,
                  thickness: 24,
                ),
                const AddMoreOrder(),
                const Divider(
                  color: backgroundColorViewBill,
                  thickness: 24,
                ),
                RincianPembayaran(
                  dataBill: dataBill,
                  totalDiscount: totalDiscount,
                  outStandingAll: outStandingAll,
                ),
                const Divider(
                  color: backgroundColorViewBill,
                  thickness: 24,
                ),
              ],
            ),
          ))
        ],
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 80,
      padding: const EdgeInsets.symmetric(horizontal: paddingLeftRight),
      // color: Colors.red,
      child: Row(
        children: [
          Expanded(
            child: defaultText(
              context,
              'Apakah anda masih ingin memesan ?',
              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,
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
