// ignore_for_file: sized_box_for_whitespace, avoid_unnecessary_containers, must_be_immutable

import 'package:byod/bloc/check_voucher.dart';
import 'package:byod/helper/helper.dart';
import 'package:byod/helper/widget/style.dart';
import 'package:byod/ui/screen_responsive.dart';
import 'package:byod/ui/viewbill/view_bill.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../../api/api.dart';
import '../../main.dart';
import '../../models/bill.dart';
import 'function.dart';
import 'list_voucher.dart';

class Payment extends StatefulWidget {
  List<Bill> dataBill;
  bool isIndividu;
  int indexIndividu;
  bool isToCashier;
  bool isVoucher;
  int outstandingIndividu;
  int outstandingAll;
  String title;
  bool isUsingBalance;
  Payment(
      {Key? key,
      required this.dataBill,
      required this.isIndividu,
      this.indexIndividu = 0,
      this.isToCashier = false,
      required this.outstandingIndividu,
      required this.outstandingAll,
      this.isVoucher = false,
      required this.title,
      this.isUsingBalance = false})
      : super(key: key);

  @override
  State<Payment> createState() => _PaymentState();
}

class _PaymentState extends State<Payment> {
  void addPaymentBalance(String orderId, String branchCode, String brandCode,
      String customerName, int amout) {
    Api.addPaymentBalance(
        context, orderId, branchCode, brandCode, customerName, amout);
  }

  final voucherController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    double widthScreen = responsiveWidthScreen(context);
    double currentScreen = MediaQuery.of(context).size.width;
    double maxWidthScreen = getMaxWidthScreen(context, useResponsive);
    double paddingLeftRight = widthScreen * 0.05;
    String branchCode = prefs.getString("outlet") ?? '';
    String brandCode = prefs.getString("brand") ?? '';
    String customerName = prefs.getString("userName") ?? '';
    context
        .read<VoucherCheck>()
        .changeVoucher(); // user dipaksa input ulang voucher
    // int totalPayment = 0;
    // if (widget.isIndividu) {
    //   for (int d = 0;
    //       d < widget.dataBill[widget.indexIndividu].billDetail.length;
    //       d++) {}
    // }
    // int individuTotalPayment = 0;
    // int individuPaymentPaid = 0;
    // int outStandingIndividu = 0;

    // int seluruhPembayaran = 0;
    // int paymentPaid = 0;

    int totalPembayaran;
    if (widget.isIndividu) {
      totalPembayaran = widget.outstandingIndividu;
      // individuTotalPayment =
      //     widget.dataBill[widget.indexIndividu].totalPerCustomer;
      // if (widget.dataBill[widget.indexIndividu].paymentList.isNotEmpty) {
      //   for (var p in widget.dataBill[widget.indexIndividu].paymentList) {
      //     if (p.customerNamePay == customerName) {
      //       individuPaymentPaid += int.parse(p.amount.split('.00')[0]);
      //     }
      //   }
      // }
      // outStandingIndividu = individuTotalPayment - individuPaymentPaid;
      // totalPembayaran = outStandingIndividu;
    } else {
      totalPembayaran = widget.outstandingAll;
      // if (widget.dataBill[0].paymentList.isNotEmpty) {
      //   for (var p in widget.dataBill[0].paymentList) {
      //     if (p.isApproved) {
      //       paymentPaid += int.parse(p.amount.split('.00')[0]);
      //     }
      //   }
      // }
      // seluruhPembayaran =
      //     int.parse(widget.dataBill[0].totalSeluruhOrderan.split('.00')[0]);
      // totalPembayaran = seluruhPembayaran - paymentPaid;
    }
    //else {
    //   for (int d = 0; d < widget.dataBill.length; d++) {
    //     for (int i = 0; i < widget.dataBill[d].billDetail.length; i++) {
    //       if (widget.dataBill[d].billDetail[i].paidStatus != successPayment) {
    //         totalPembayaran += int.parse(
    //             widget.dataBill[d].billDetail[i].total.split('.00')[0]);
    //       }
    //     }
    //   }
    // }
    return SafeArea(
        child: Scaffold(
      backgroundColor: backgroundColor,
      body: ScreenResponsive(
        widget: corePayment(
          paddingLeftRight,
          totalPembayaran,
          widthScreen,
          branchCode,
          brandCode,
          customerName,
          maxWidthScreen,
        ),
        widthScreen: currentScreen,
        isCoreLayout: true,
      ),
    ));
  }

  Center corePayment(
    double paddingLeftRight,
    int totalPembayaran,
    double widthScreen,
    String branchCode,
    String brandCode,
    String customerName,
    double maxWidthScreen,
  ) {
    return Center(
      child: Container(
        // margin: const EdgeInsets.only(left: 10, right: 10),
        // color: Colors.red,

        width: (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
        padding: EdgeInsets.symmetric(
          horizontal: paddingLeftRight,
        ),
        child: BlocBuilder<VoucherCheck, List<dynamic>>(
          builder: (context, listVoucher) {
            bool enabledTextField = true;
            int voucherNominal = 0;
            if (listVoucher.isNotEmpty && listVoucher[0] != '0') {
              voucherNominal = amountParseToInt(listVoucher[1]);
              enabledTextField = false;
            }
            int totalPayment = 0;
            if ((totalPembayaran - voucherNominal) < 0) {
              totalPayment = 0;
            } else if (widget.isVoucher) {
              totalPayment = voucherNominal;
            } else {
              totalPayment = totalPembayaran - voucherNominal;
            }
            return Stack(
              children: [
                Column(
                  children: [
                    customAppbar(
                      context,
                      widget.title,
                      widthScreen,
                      maxWidthScreen,
                    ),
                    // (widget.isIndividu)
                    //     ? widget
                    //         .dataBill[widget.indexIndividu].customerName
                    //     : (widget.isVoucher)
                    //         ? 'Voucher'
                    //         : "Bayar Semua Bill"),
                    Container(
                        height: MediaQuery.of(context).size.height * 0.92,
                        // margin: const EdgeInsets.only(left: 5, right: 5),
                        // padding: EdgeInsets.symmetric(
                        //   horizontal: paddingLeftRight,
                        // ),
                        // color: Colors.red,
                        child: Column(
                          children: [
                            // listViewOrdersPerPerson(widget.dataBill,
                            //     widget.isIndividu, widget.indexIndividu),
                            (widget.isVoucher)
                                ? Container(
                                    child: Row(
                                      children: [
                                        Container(
                                          width: widthScreen * 0.7,
                                          height: MediaQuery.of(context)
                                                  .size
                                                  .height *
                                              0.06,
                                          child: TextField(
                                            enabled: enabledTextField,
                                            // autofocus: true,
                                            keyboardType: TextInputType.text,
                                            controller:
                                                (listVoucher.isNotEmpty &&
                                                        listVoucher[0] != '0')
                                                    ? TextEditingController(
                                                        text: listVoucher[0])
                                                    : voucherController,
                                            // style: const TextStyle(
                                            //   color: Colors.black,
                                            //   fontSize: 18,
                                            //   fontWeight: FontWeight.w400,
                                            // ),
                                            style: textStyleNormalFont(context),
                                            decoration: InputDecoration(
                                              focusedBorder: OutlineInputBorder(
                                                  borderRadius:
                                                      BorderRadius.all(
                                                          Radius.circular(
                                                              roundedButton)),
                                                  borderSide: BorderSide(
                                                      color: buttonColor,
                                                      width: 2.0)),
                                              enabledBorder: OutlineInputBorder(
                                                  borderRadius:
                                                      BorderRadius.all(
                                                          Radius.circular(
                                                              roundedButton)),
                                                  borderSide: BorderSide(
                                                      color: buttonColor,
                                                      width: 2.0)),
                                              // border: InputBorder.none,
                                              hintText: "Masukkan Kode Voucher",
                                              hintStyle: TextStyle(
                                                color: Colors.grey,
                                                fontSize: MediaQuery.of(context)
                                                        .size
                                                        .height *
                                                    normalFont,
                                              ),
                                            ),
                                          ),
                                        ),
                                        SizedBox(
                                          width: widthScreen * 0.005,
                                        ),
                                        GestureDetector(
                                          onTap: () {
                                            if (enabledTextField) {
                                              if (voucherController
                                                  .text.isEmpty) {
                                                EasyLoading.showToast(
                                                    'Kode voucher harus diisi');
                                              } else {
                                                context
                                                    .read<VoucherCheck>()
                                                    .check(
                                                        voucherController.text);
                                              }
                                            } else {
                                              context
                                                  .read<VoucherCheck>()
                                                  .changeVoucher();
                                            }
                                          },
                                          child: Container(
                                            width: widthScreen * 0.19,
                                            height: MediaQuery.of(context)
                                                    .size
                                                    .height *
                                                0.06,
                                            decoration: BoxDecoration(
                                                borderRadius:
                                                    BorderRadius.circular(
                                                        roundedButton),
                                                color: buttonColor),
                                            child: Center(
                                              // child: Text(
                                              //   (enabledTextField)
                                              //       ? "Check"
                                              //       : "Ganti",
                                              //   // style: const TextStyle(
                                              //   //     color: textInButton,
                                              //   //     fontWeight:
                                              //   //         FontWeight.w500),
                                              //   style: textStyleNormalFont(
                                              //     context,
                                              //     color: textInButton,
                                              //   ),
                                              // ),
                                              child: defaultText(
                                                context,
                                                (enabledTextField)
                                                    ? "Check"
                                                    : "Ganti",
                                                style: textStyleNormalFont(
                                                  context,
                                                  color: textInButton,
                                                ),
                                              ),
                                            ),
                                          ),
                                        )
                                      ],
                                    ),
                                  )
                                : const SizedBox(),
                            BoxPaymentDetail(
                              widget: widget,
                              totalPayment: totalPayment,
                              widthScreen: widthScreen,
                            ),
                            (widget.isVoucher)
                                ? ListVoucher(
                                    widget: widget,
                                    widthScreen: widthScreen,
                                    listVoucher: listVoucher,
                                  )
                                : const SizedBox()
                          ],
                        )),
                  ],
                ),
                Positioned(
                  bottom: MediaQuery.of(context).size.height * positionedBottom,
                  child: AnimatedSwitcher(
                    duration: Duration(milliseconds: animatedTime),
                    transitionBuilder: (child, animation) =>
                        ScaleTransition(scale: animation, child: child),
                    child: Column(
                      children: [
                        GestureDetector(
                          onTap: () {
                            // if (totalPayment > 0) {
                            if (widget.isVoucher) {
                              if (listVoucher.isNotEmpty &&
                                  listVoucher[0] != '0') {
                                // if (voucherNominal > totalPembayaran) {
                                //   EasyLoading.showInfo(
                                //       'Total Tagihan Lebih Kecil Daripada Nominal Voucher');
                                // } else {
                                addPayment(
                                  context,
                                  widget.dataBill[0].id,
                                  branchCode,
                                  brandCode,
                                  customerName,
                                  payVoucher,
                                  fullPayment,
                                  listVoucher[2],
                                  voucherNominal,
                                );
                                // }
                              }
                              // else {
                              //   EasyLoading.showToast(
                              //       'Voucher belum diisi');
                              // }
                            } else if (widget.isIndividu) {
                              if (widget.isUsingBalance) {
                                // using balance karena hanya excelso untuk saat ini jadi overide outstandingindividu dulu
                                addPaymentBalance(
                                  widget.dataBill[0].id,
                                  branchCode,
                                  brandCode,
                                  customerName,
                                  widget.outstandingIndividu,
                                );
                              } else {
                                addPayment(
                                  context,
                                  widget.dataBill[0].id,
                                  branchCode,
                                  brandCode,
                                  customerName,
                                  payCard,
                                  partialPayment,
                                  '',
                                  widget.outstandingIndividu,
                                );
                              }
                            } else {
                              addPayment(
                                context,
                                widget.dataBill[0].id,
                                branchCode,
                                brandCode,
                                customerName,
                                payCard,
                                fullPayment,
                                '',
                                widget.outstandingAll,
                              );
                            }
                          },
                          child: buttonBottom(
                            context,
                            (widget.isVoucher) ? 'Gunakan Voucher' : 'Bayar',
                            (widget.isVoucher &&
                                    listVoucher.isNotEmpty &&
                                    listVoucher[0] != '0')
                                ? buttonColor
                                : (!widget.isVoucher)
                                    ? buttonColor
                                    : disabledColor,
                            0.9,
                          ),
                        ),
                        SizedBox(
                          height: MediaQuery.of(context).size.height * 0.01,
                        ),
                        GestureDetector(
                          onTap: () {
                            Navigator.pushReplacement(context,
                                MaterialPageRoute(builder: (_) => ViewBill()));
                          },
                          // child: Container(
                          //   height:
                          //       MediaQuery.of(context).size.height * 0.08,
                          //   width:
                          //       MediaQuery.of(context).size.width * 0.95,
                          //   decoration: BoxDecoration(
                          //     borderRadius:
                          //         BorderRadius.circular(roundedButton),
                          //     color: cancelColor,
                          //   ),
                          //   child: Container(
                          //     margin: const EdgeInsets.all(5),
                          //     // color: Colors.red,
                          //     child: Align(
                          //         alignment: Alignment.center,
                          //         child: Text(
                          //           "Batal",
                          //           // style: TextStyle(
                          //           //     fontWeight: FontWeight.w500,
                          //           //     fontSize: 18,
                          //           //     color: textInButton),
                          //           style: textStyleNormalFont(
                          //             context,
                          //             color: textInButton,
                          //           ),
                          //         )),
                          //   ),
                          // ),
                          child: buttonBottom(
                            context,
                            'Batal',
                            cancelColorButton,
                            0.9,
                            colorText: textCancelColor,
                          ),
                        )
                      ],
                    ),
                  ),
                )
              ],
            );
          },
        ),
      ),
    );
  }

  Container customAppbar(BuildContext context, String namaCustomer,
      double widthScreen, double maxWidthScreen) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.08,
      width: (widthScreen > maxWidthScreen) ? maxWidthScreen : widthScreen,
      // color: Colors.amber,
      child: Row(
        // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          GestureDetector(
            onTap: () {
              Navigator.pushReplacement(
                  context, MaterialPageRoute(builder: (_) => ViewBill()));
            },
            child: Container(
              // color: Colors.white,
              height: double.infinity,
              width: widthScreen * 0.2,
              // child: const Icon(Icons.arrow_back_ios_new_rounded),
              child: Align(
                alignment: Alignment.center,
                child: fontAwesome(
                  context,
                  backIcon,
                  backIconSize,
                ),
              ),
            ),
          ),
          Container(
            // color: Colors.red,
            height: double.infinity,
            width: widthScreen * 0.7,
            child: Align(
                alignment: Alignment.centerLeft,
                // child: Text(
                //   'Konfirmasi Pembayaran',
                //   overflow: TextOverflow.ellipsis,
                //   maxLines: 1,
                //   // style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
                //   style: textStyleMenuList(context),
                // )
                child: defaultText(
                  context,
                  'Konfirmasi Pembayaran',
                  overFlow: TextOverflow.ellipsis,
                  maxLines: 1,
                  style: textStyleMenuList(context),
                )),
          ),
        ],
      ),
    );
  }

  // ListView listViewOrdersPerPerson(
  //     List<Bill> databill, bool isIndividu, int indexIndividu) {
  //   return ListView.builder(
  //     physics:
  //         const NeverScrollableScrollPhysics(), // to disable GridView's scrolling
  //     shrinkWrap: true,
  //     itemCount: (isIndividu) ? 1 : databill.length,
  //     itemBuilder: (context, i) {
  //       return Column(
  //         children: [
  //           listViewOrders((isIndividu)
  //               ? databill[indexIndividu].billDetail
  //               : databill[i].billDetail)
  //         ],
  //       );
  //     },
  //   );
  // }

  // ListView listViewOrders(List<BillDetail> billDetail) {
  //   List<BillDetail> billDetailNotPaid = [];
  //   // for (int d = 0; d < billDetail.length; d++) {
  //   //   if (billDetail[d].paidStatus != successPayment) {
  //   //     billDetailNotPaid.add(billDetail[d]);
  //   //   }
  //   // }
  //   return ListView.builder(
  //       // controller: _scrollController,
  //       physics:
  //           const NeverScrollableScrollPhysics(), // to disable GridView's scrolling
  //       shrinkWrap: true,
  //       itemCount: billDetailNotPaid
  //           .length, // harus sama dengan item count dibawah, tujuan layouting
  //       itemBuilder: (context, x) {
  //         return OrderViewBill(
  //           billDetail: billDetailNotPaid[x],
  //           itemKe: x + 1,
  //           itemCount: billDetailNotPaid.length,
  //           isFromPayment: true,
  //         );
  //       });
  // }
}

class BoxPaymentDetail extends StatelessWidget {
  const BoxPaymentDetail({
    Key? key,
    required this.widget,
    required this.totalPayment,
    required this.widthScreen,
  }) : super(key: key);

  final Payment widget;
  final int totalPayment;
  final double widthScreen;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(
        top: MediaQuery.of(context).size.height * 0.01,
        // bottom: MediaQuery.of(context).size.height * 0.1,
      ),
      padding: EdgeInsets.symmetric(
        horizontal: widthScreen * 0.03,
        vertical: MediaQuery.of(context).size.height * 0.015,
      ),
      height: MediaQuery.of(context).size.height * 0.15,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(roundedDetailPayment),
        color: Colors.grey[200],
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // Container(
          //   height:
          //       MediaQuery.of(context).size.height *
          //           0.06,
          //   margin: const EdgeInsets.only(top: 10),
          //   width: double.infinity,
          //   // color: Colors.red,
          //   child: const Text(
          //     "Payment Summary",
          //     style: TextStyle(
          //         fontWeight: FontWeight.w600,
          //         fontSize: 20),
          //   ),
          // ),
          Container(
            height: MediaQuery.of(context).size.height * 0.04,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  // child: Text(
                  //   "Unpaid",
                  //   // style: TextStyle(
                  //   //     fontWeight: FontWeight.w500,
                  //   //     fontSize: 18),
                  //   style:
                  //       textStyleNormalFont(context),
                  // ),
                  child: defaultText(
                    context,
                    "Unpaid",
                    style: textStyleNormalFont(context),
                  ),
                ),
                // Text(
                //   "Rp ${formatNumber().format(widget.outstandingAll)}",
                //   // style: const TextStyle(
                //   //     fontWeight: FontWeight.w500,
                //   //     fontSize: 18),
                //   style: textStyleNormalFont(context),
                // ),
                defaultText(
                  context,
                  "Rp ${formatNumber().format(widget.outstandingAll)}",
                  style: textStyleNormalFont(context),
                )
              ],
            ),
          ),
          // (widget.isVoucher)
          //     ? SizedBox(
          //         height: MediaQuery.of(context)
          //                 .size
          //                 .height *
          //             0.04,
          //         child: Row(
          //           mainAxisAlignment:
          //               MainAxisAlignment
          //                   .spaceBetween,
          //           children: [
          //             Container(
          //               child: const Text(
          //                 "Voucher",
          //                 style: TextStyle(
          //                     fontWeight:
          //                         FontWeight.w500,
          //                     fontSize: 18),
          //               ),
          //             ),
          //             Container(
          //               child: Text(
          //                 "Rp ${formatNumber().format(voucherNominal)}",
          //                 style: const TextStyle(
          //                     fontWeight:
          //                         FontWeight.w500,
          //                     fontSize: 18),
          //               ),
          //             ),
          //           ],
          //         ),
          //       )
          //     : const SizedBox(),
          SizedBox(
            height: MediaQuery.of(context).size.height * 0.005,
          ),
          Divider(
            height: MediaQuery.of(context).size.height * 0.01,
            color: Colors.grey,
          ),
          SizedBox(
            height: MediaQuery.of(context).size.height * 0.005,
          ),
          Container(
            height: MediaQuery.of(context).size.height * 0.04,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                    // child: Text(
                    //   // (widget.isVoucher)
                    //   //     ? "Sisa Bayar"
                    //   //     : "Total",
                    //   "Nilai Bayar",
                    //   // style: TextStyle(
                    //   //     fontWeight: FontWeight.w600,
                    //   //     fontSize: 18),
                    //   style: textStyleNormalFont(
                    //     context,
                    //     isBold: true,
                    //   ),
                    // ),
                    child: defaultText(
                  context,
                  "Nilai Bayar",
                  style: textStyleNormalFont(
                    context,
                    isBold: true,
                  ),
                )),
                Container(
                    // child: Text(
                    //   "Rp ${formatNumber().format(totalPayment)}",
                    //   // style: const TextStyle(
                    //   //     fontWeight: FontWeight.w600,
                    //   //     fontSize: 18),
                    //   style: textStyleNormalFont(
                    //     context,
                    //     isBold: true,
                    //   ),
                    // ),
                    child: defaultText(
                  context,
                  "Rp ${formatNumber().format(totalPayment)}",
                  style: textStyleNormalFont(
                    context,
                    isBold: true,
                  ),
                )),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
