// ignore_for_file: sized_box_for_whitespace

import 'package:byod/bloc/check_voucher.dart';
import 'package:byod/bloc/voucher_list.dart';
import 'package:byod/helper/helper.dart';
import 'package:byod/helper/widget/button_modal.dart';
import 'package:byod/main.dart';
import 'package:byod/ui/screen_responsive.dart';
import 'package:byod/ui/viewbill/view_bill_new.dart';
import 'package:dotted_line/dotted_line.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../../helper/widget/style.dart';
import '../../models/bill.dart';
import '../../models/voucher_list.dart';
import 'function.dart';

class PaymentVoucher extends StatelessWidget {
  const PaymentVoucher(
      {super.key, required this.outstandingAll, required this.dataBill});

  final int outstandingAll;
  final List<Bill> dataBill;

  @override
  Widget build(BuildContext context) {
    context.read<VoucherCheck>().changeVoucher();
    double currentScreen = MediaQuery.of(context).size.width;
    return SafeArea(
      child: Scaffold(
        backgroundColor: backgroundColor,
        body: ScreenResponsive(
          widget: CorePaymentVoucher(
            outstandingAll: outstandingAll,
            dataBill: dataBill,
          ),
          isCoreLayout: true,
          widthScreen: currentScreen,
        ),
      ),
    );
  }
}

class CorePaymentVoucher extends StatelessWidget {
  CorePaymentVoucher(
      {super.key, required this.outstandingAll, required this.dataBill});

  final int outstandingAll;
  final List<Bill> dataBill;

  final String branchCode = prefs.getString("outlet") ?? '';
  final String brandCode = prefs.getString("brand") ?? '';
  final String customerName = prefs.getString("userName") ?? '';
  @override
  Widget build(BuildContext context) {
    double widthScreen = responsiveWidthScreen(context);
    String logoUrl = prefs.getString('logoUrl') ?? '';
    return Container(
      width: widthScreen,
      child: BlocBuilder<VoucherCheck, List<dynamic>>(
        builder: (ctxVocherCheck, listVoucher) {
          return Stack(
            children: [
              Column(
                children: [
                  CustomAppBarVoucher(
                    listVoucher: listVoucher,
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  RincianPembayaranVoucher(
                    listVoucher: listVoucher,
                    outstandingAll: outstandingAll,
                  ),
                  const SizedBox(
                    height: 16,
                  ),
                  BlocBuilder<VoucherListBloc, List<VoucherList>>(
                    builder: (contextVoucherListBloc, voucherListData) {
                      return Expanded(
                        child: ListView.builder(
                          itemCount: voucherListData.length,
                          itemBuilder: (ctxVoucherList, i) {
                            // String minTransaction;
                            int valueMinTransaction;
                            if (voucherListData[i].minTransaction >
                                voucherListData[i].value) {
                              valueMinTransaction =
                                  voucherListData[i].minTransaction;
                              // minTransaction =
                              //     "Min Transaksi ${formatNumber().format(valueMinTransaction)}";
                              // minTransaction =
                              //     " ${formatNumber().format(valueMinTransaction)}";
                            } else {
                              valueMinTransaction = voucherListData[i].value;
                              // minTransaction =
                              //     "Min Transaksi ${formatNumber().format(valueMinTransaction)}";
                            }
                            bool isCanSelect = true;
                            if (outstandingAll <
                                    voucherListData[i].minTransaction ||
                                outstandingAll < voucherListData[i].value) {
                              isCanSelect = false;
                            }
                            return GestureDetector(
                              onTap: () {
                                if (isCanSelect) {
                                  if (listVoucher.isNotEmpty &&
                                      listVoucher[0] != '0' &&
                                      listVoucher[2] ==
                                          voucherListData[i]
                                              .verificationNumber) {
                                    context
                                        .read<VoucherCheck>()
                                        .changeVoucher();
                                  } else {
                                    context.read<VoucherCheck>().check(
                                        voucherListData[i].verificationNumber);
                                  }
                                } else {
                                  EasyLoading.showToast(
                                      "Tambah minimal ${formatNumber().format(valueMinTransaction - outstandingAll)} untuk menggunakan voucher");
                                }
                              },
                              child: ListVoucherView(
                                logoUrl: logoUrl,
                                valueMinTransaction: valueMinTransaction,
                                outstandingAll: outstandingAll,
                                isCanSelect: isCanSelect,
                                voucherListData: voucherListData,
                                index: i,
                                listVoucher: listVoucher,
                              ),
                            );
                          },
                        ),
                      );
                    },
                  )
                ],
              ),
              Positioned(
                bottom: 0,
                child: GestureDetector(
                  onTap: () {
                    if (listVoucher.isNotEmpty && listVoucher[0] != '0') {
                      // if (voucherNominal > totalPembayaran) {
                      //   EasyLoading.showInfo(
                      //       'Total Tagihan Lebih Kecil Daripada Nominal Voucher');
                      // } else {
                      addPayment(
                        context,
                        dataBill[0].id,
                        branchCode,
                        brandCode,
                        customerName,
                        payVoucher,
                        fullPayment,
                        listVoucher[2],
                        amountParseToInt(listVoucher[1]),
                      );
                      // }
                    }
                  },
                  child: Container(
                    width: widthScreen,
                    color: backgroundWhite,
                    padding: const EdgeInsets.symmetric(
                        horizontal: paddingLeftRight, vertical: 16),
                    child: ButtonComponent(
                      buttonColor:
                          (listVoucher.isNotEmpty && listVoucher[0] != '0')
                              ? buttonColor
                              : disabledColor,
                      teksButton: 'Gunakan Voucher',
                    ),
                  ),
                ),
              )
            ],
          );
        },
      ),
    );
  }
}

class ListVoucherView extends StatelessWidget {
  const ListVoucherView({
    Key? key,
    required this.logoUrl,
    required this.valueMinTransaction,
    required this.outstandingAll,
    required this.isCanSelect,
    required this.voucherListData,
    required this.index,
    required this.listVoucher,
  }) : super(key: key);

  final String logoUrl;
  final int valueMinTransaction;
  final int outstandingAll;
  final bool isCanSelect;
  final List<VoucherList> voucherListData;
  final int index;
  final List<dynamic> listVoucher;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        color: (listVoucher.isNotEmpty &&
                listVoucher[0] != '0' &&
                listVoucher[2] == voucherListData[index].verificationNumber)
            ? selectedColorVoucher
            : backgroundWhite,
      ),
      padding: const EdgeInsets.only(
        top: 16,
        left: 16,
        right: 16,
      ),
      margin: EdgeInsets.only(
        left: paddingLeftRight,
        right: paddingLeftRight,
        bottom: (index + 1 == voucherListData.length) ? 80 : 12,
      ),
      child: Column(
        children: [
          Container(
            height: 72,
            width: double.infinity,
            decoration: BoxDecoration(
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(8),
                topRight: Radius.circular(8),
              ),
              image: (voucherListData[index].titleImageUrl != '')
                  ? DecorationImage(
                      colorFilter: (!isCanSelect)
                          ? const ColorFilter.mode(
                              Colors.grey,
                              BlendMode.saturation,
                            )
                          : null,
                      fit: BoxFit.fill,
                      image: NetworkImage(
                        voucherListData[index].titleImageUrl,
                      ),
                    )
                  : null,
            ),

            // child: const ClipRRect(
            //   borderRadius: BorderRadius.only(
            //     topLeft: Radius.circular(8),
            //     topRight: Radius.circular(8),
            //   ),
            //   child: Image(
            //     fit: BoxFit.fill,
            //     image: NetworkImage(
            //         'https://bandar-media.s3.amazonaws.com/member/7fc891b5-712c-4962-82e1-447261bc2601-title.jpg'),
            //   ),
            // ),
          ),
          const SizedBox(
            height: 7,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                width: 111,
                height: 42,
                color: (listVoucher.isNotEmpty &&
                        listVoucher[0] != '0' &&
                        listVoucher[2] ==
                            voucherListData[index].verificationNumber)
                    ? selectedColorVoucher
                    : backgroundWhite,
                child: Image(
                  width: 111,
                  height: 42,
                  image: NetworkImage(logoUrl),
                ),
              ),
              Container(
                width: 108,
                child: defaultText(
                  context,
                  voucherListData[index].rewardTitle,
                  textAlign: TextAlign.right,
                  style: rincianPembayaran(
                    font: 14,
                  ),
                ),
              )
            ],
          ),
          const SizedBox(
            height: 12,
          ),
          const DottedLine(
            dashColor: dashGrey,
            dashLength: 12,
          ),
          const SizedBox(
            height: 12,
          ),
          Row(
            children: [
              Image(
                width: 20,
                height: 20,
                image: AssetImage((isExcelso)
                    ? 'assets/icons/clock-gold.png'
                    : 'assets/icons/clock.png'),
              ),
              const SizedBox(
                width: 14,
              ),
              defaultText(
                context,
                formatDate(
                  voucherListData[index].expired,
                  toLocal: true,
                ),
                style: addButton(
                  font: 12,
                  color: textColorBlack,
                ),
              ),
              const Spacer(),
              Container(
                height: 30,
                width: 98,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(21),
                  color: (listVoucher.isNotEmpty &&
                          listVoucher[0] != '0' &&
                          listVoucher[2] ==
                              voucherListData[index].verificationNumber)
                      ? disabledColor
                      : buttonColor,
                ),
                child: Center(
                  child: defaultText(
                    context,
                    (listVoucher.isNotEmpty &&
                            listVoucher[0] != '0' &&
                            listVoucher[2] ==
                                voucherListData[index].verificationNumber)
                        ? 'Batal'
                        : 'Pakai',
                    style: addButton(font: 8),
                  ),
                ),
              )
            ],
          ),
          (!isCanSelect)
              ? Column(
                  children: [
                    const SizedBox(
                      height: 16,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        fontAwesome(
                          context,
                          infoCircle,
                          infoCircleSize,
                          color: Colors.grey,
                        ),
                        const SizedBox(
                          width: 10,
                        ),
                        defaultText(
                          context,
                          'Tambah minimal ${formatNumber().format(valueMinTransaction - outstandingAll)} untuk menggunakan voucher',
                          style: textStyleVoucherListAddMore(context),
                        ),
                      ],
                    ),
                  ],
                )
              : const SizedBox(),
          const SizedBox(
            height: 20,
          ),
        ],
      ),
    );
  }
}

class RincianPembayaranVoucher extends StatelessWidget {
  const RincianPembayaranVoucher({
    Key? key,
    required this.listVoucher,
    required this.outstandingAll,
  }) : super(key: key);

  final List<dynamic> listVoucher;
  final int outstandingAll;
  @override
  Widget build(BuildContext context) {
    int voucherNominal = 0;
    if (listVoucher.isNotEmpty && listVoucher[0] != '0') {
      voucherNominal = amountParseToInt(listVoucher[1]);
    }
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        color: backgroundWhite,
      ),
      padding: const EdgeInsets.all(16),
      margin: const EdgeInsets.symmetric(horizontal: paddingLeftRight),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          defaultText(
            context,
            'Rincian Pembayaran',
            style: rincianPembayaran(
              font: 14,
            ),
          ),
          (listVoucher.isNotEmpty && listVoucher[0] != '0')
              ? Column(
                  children: [
                    const SizedBox(
                      height: 16,
                    ),
                    const Divider(
                      thickness: 1,
                      color: dividerGrey2,
                    ),
                    const SizedBox(
                      height: 12,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        defaultText(
                          context,
                          'Discount E-Voucher',
                          style: rincianPembayaran(
                            font: 12,
                            color: textGreyBill,
                          ),
                        ),
                        defaultText(
                          context,
                          "Rp ${formatNumber().format(voucherNominal)}",
                          style: rincianPembayaran(
                            font: 12,
                            color: textGreyBill,
                          ),
                        )
                      ],
                    ),
                  ],
                )
              : const SizedBox(),
          const SizedBox(
            height: 16,
          ),
          const Divider(
            thickness: 1,
            color: dividerGrey2,
          ),
          const SizedBox(
            height: 12,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              defaultText(
                context,
                'Total Harga',
                style: rincianPembayaran(
                  font: 14,
                ),
              ),
              defaultText(
                context,
                "Rp ${formatNumber().format(outstandingAll)}",
                style: rincianPembayaran(
                  font: 14,
                ),
              )
            ],
          )
        ],
      ),
    );
  }
}

class CustomAppBarVoucher extends StatelessWidget {
  CustomAppBarVoucher({
    Key? key,
    required this.listVoucher,
  }) : super(key: key);

  final List<dynamic> listVoucher;
  final TextEditingController voucherController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    bool enabledTextField = true;
    if (listVoucher.isNotEmpty && listVoucher[0] != '0') {
      enabledTextField = false;
    }
    return Container(
      padding: const EdgeInsets.only(
        top: 15,
        bottom: 17,
        left: paddingLeftRight,
        right: paddingLeftRight,
      ),
      // padding: const EdgeInsets.symmetric(horizontal: paddingLeftRight),
      color: backgroundWhite,
      child: Column(
        children: [
          Row(
            // mainAxisAlignment: MainAxisAlignment.start,
            children: [
              GestureDetector(
                onTap: () {
                  Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(builder: (_) => const ViewBillNew()),
                  );
                },
                child: Container(
                  width: 24,
                  height: 24,
                  child: Center(
                    child: fontAwesomeNew(
                      arrowBack,
                      arrowBackSize,
                    ),
                  ),
                ),
              ),
              const SizedBox(
                width: 16,
              ),
              Center(
                child: defaultText(
                  context,
                  'Voucher',
                  maxLines: 1,
                  overFlow: TextOverflow.ellipsis,
                  style: appBarNameViewBill(),
                ),
              ),
            ],
          ),
          const SizedBox(
            height: 16,
          ),
          Row(
            children: [
              Expanded(
                child: Container(
                  width: 236,
                  height: 36,
                  child: TextField(
                    controller:
                        (listVoucher.isNotEmpty && listVoucher[0] != '0')
                            ? TextEditingController(text: listVoucher[0])
                            : voucherController,
                    // autofocus: true,
                    enabled: enabledTextField,
                    style: TextStyle(
                      color: Colors.black,
                      fontFamily: fontFamily,
                      fontSize: 15,
                    ),
                    textAlignVertical: TextAlignVertical.center,
                    decoration: InputDecoration(
                      // hintText: 'Kode Voucher',
                      filled: true,
                      fillColor: Colors.white,
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(
                          width: 1,
                          color: Colors.grey.withOpacity(0.8),
                        ),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(
                          width: 1,
                          color: buttonColor,
                        ),
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(6),
                      ),
                      contentPadding: const EdgeInsets.all(5),
                    ),
                  ),
                ),
              ),
              const SizedBox(
                width: 12,
              ),
              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(
                  height: 36,
                  width: 87,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    color: buttonColor,
                  ),
                  child: Center(
                    child: defaultText(
                      context,
                      (enabledTextField) ? 'Redeem' : 'Ganti',
                      style: addButton(
                        font: 8,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
