import 'package:cherry_toast/cherry_toast.dart';
import 'package:cherry_toast/resources/arrays.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:initial_folder/base_service.dart';
import 'package:initial_folder/models/history_transaction_model.dart';
import 'package:initial_folder/screens/profile/account_sign_in/invoice.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/custom_navigator.dart';
import 'package:initial_folder/widgets/login_regist/default_button_payment.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:initial_folder/providers/detail_invoice_provider.dart'
    as detailProvs;

class DetailPembelianSukses extends StatefulWidget {
  DetailPembelianSukses({
    Key? key,
    this.orderId,
    this.dataHistoryTransactionModel,
  }) : super(key: key);

  final String? orderId;
  final HistoryTransactionModel? dataHistoryTransactionModel;

  final Map<String, String> status = {
    'null': "Dibatalkan",
    '1': 'Berhasil',
    '0': 'Transaksi Kursus Gratis',
    '2': 'Menunggu Pembayaran',
    '-1': 'Pembayaran Ditolak',
    '-2': 'Melebihi Batas Waktu',
  };

  final Map<String, String> paymentType = {
    'null': "Dibatalkan",
    'bank transfer': 'Bank Transfer',
    'echannel': 'Bank Transfer',
    'credit card': 'Kartu Kredit',
    'permata': 'Bank Transfer',
    'gopay': 'GoPay',
    'cstore': 'Gerai',
    'free': 'Kursus Gratis',
    'Coupon Free Course': 'Kursus Gratis'
  };

  @override
  State<DetailPembelianSukses> createState() => _DetailPembelianSuksesState();
}

class _DetailPembelianSuksesState extends State<DetailPembelianSukses> {
  bool isButtonPressed = false;
  final TextStyle baris = primaryTextStyle.copyWith(
    fontWeight: reguler,
    fontSize: getProportionateScreenWidth(14),
    letterSpacing: 0.5,
  );

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (widget.orderId!.isNotEmpty) {
        try {
          Provider.of<detailProvs.DetailInvoiceProvider>(context, listen: false)
              .fetchDetailInvoice(widget.orderId);
        } catch (e) {
          print('Gagal detail invoice $e');
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        scrolledUnderElevation: 0.0,
        backgroundColor: Theme.of(context).colorScheme.background,
        title: Text(
          "Cara Pembayaran",
          style: thirdTextStyle.copyWith(
            fontWeight: semiBold,
            fontSize: getProportionateScreenWidth(15),
          ),
        ),
      ),
      body: SingleChildScrollView(
        child: Consumer<detailProvs.DetailInvoiceProvider>(
          builder: (context, provider, child) {
            if (provider.state == detailProvs.ResultState.loading) {
              return Center(
                child: Column(
                  children: [
                    Padding(
                      padding: EdgeInsets.only(
                          top: getProportionateScreenHeight(100)),
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        color: primaryColor,
                      ),
                    ),
                  ],
                ),
              );
            } else if (provider.state == detailProvs.ResultState.hasData) {
              Widget buildTextWidget() {
                String text = "";
                if (provider.detailInvoice?[0].permataVaNumber != null) {
                  text = "Permata Virtual Account";
                } else if (provider.detailInvoice?[0].billerCode != null) {
                  text = "Mandiri Virtual Account";
                } else if (provider.detailInvoice?[0].vaNumbers != null &&
                    provider.detailInvoice![0].vaNumbers!
                        .any((va) => va.bank == 'bni')) {
                  text = "BNI Virtual Account";
                } else if (provider.detailInvoice?[0].vaNumbers != null &&
                    provider.detailInvoice![0].vaNumbers!
                        .any((va) => va.bank == 'bca')) {
                  text = "BCA Virtual Account";
                } else if (provider.detailInvoice?[0].billerCode != null) {
                  text = "Mandiri Virtual Account";
                } else if (provider.detailInvoice?[0].store == "alfamart") {
                  text = "Alfamart";
                } else if (provider.detailInvoice?[0].store == "indomaret") {
                  text = "Indomart";
                } else if (provider.detailInvoice?[0].paymentType ==
                    "credit_card") {
                  text = "Credit Card";
                } else if (provider.detailInvoice?[0].paymentType == "gopay") {
                  text = "QRIS";
                } else {
                  "Transaksi Gratis";
                }
                return Text(
                  text ?? "Transaksi Gratis",
                  style: thirdTextStyle.copyWith(
                      fontSize: getProportionateScreenWidth(11)),
                );
              }

              return Padding(
                padding: EdgeInsets.symmetric(
                  horizontal: getProportionateScreenWidth(10),
                  vertical: getProportionateScreenHeight(10),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      width: double.infinity,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(4),
                          topRight: Radius.circular(4),
                        ),
                        color: Theme.of(context).colorScheme.primaryContainer,
                      ),
                      padding: EdgeInsets.only(
                        left: getProportionateScreenWidth(10),
                        right: getProportionateScreenWidth(10),
                        top: getProportionateScreenHeight(15),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                'Transaksi Selesai',
                                style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(13),
                                ),
                              ),
                              if (widget
                                          .dataHistoryTransactionModel?.statusPayment ==
                                      '1' ||
                                  widget.dataHistoryTransactionModel
                                          ?.statusPayment ==
                                      '0')
                                _statusLabel(
                                    widget.status[widget.dataHistoryTransactionModel?.statusPayment] ??
                                        '',
                                    eightColor)
                              else if (widget.dataHistoryTransactionModel!.statusPayment == '2' ||
                                  widget.dataHistoryTransactionModel!.statusPayment ==
                                      '0')
                                _statusLabel(
                                    widget.status[widget.dataHistoryTransactionModel?.statusPayment] ??
                                        '',
                                    fiveColor)
                              else if (widget.dataHistoryTransactionModel!
                                          .statusPayment !=
                                      null &&
                                  widget.status.containsKey(
                                      widget.dataHistoryTransactionModel!.statusPayment))
                                _statusLabel(widget.status[widget.dataHistoryTransactionModel?.statusPayment] ?? '', sevenColor)
                              else
                                _statusLabel(widget.status['null']! ?? "null", sevenColor)
                            ],
                          ),
                          SizedBox(height: getProportionateScreenHeight(8)),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                'Order ID',
                                style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(11),
                                ),
                              ),
                              Text(
                                widget.orderId!,
                                style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(11),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: getProportionateScreenHeight(5)),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                'Tanggal Pembelian',
                                style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(11),
                                ),
                              ),
                              Text(
                                DateFormat('E, d MMM y').format(DateTime.parse(
                                    widget.dataHistoryTransactionModel!.date
                                        .toString())),
                                style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(11),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    Container(
                      width: double.infinity,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(4),
                          bottomRight: Radius.circular(4),
                        ),
                        color: Theme.of(context).colorScheme.primaryContainer,
                        boxShadow: [
                          BoxShadow(
                            color:
                                Theme.of(context).brightness == Brightness.dark
                                    ? Colors.transparent
                                    : secondaryColor.withOpacity(0.2),
                            spreadRadius: 1,
                            blurRadius: 2,
                            offset: Offset(0, getProportionateScreenHeight(4)),
                          ),
                        ],
                      ),
                      padding: EdgeInsets.symmetric(
                          horizontal: getProportionateScreenWidth(10)),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(height: getProportionateScreenHeight(10)),
                          Text(
                            "Kursus",
                            style: thirdTextStyle.copyWith(
                                fontSize: getProportionateScreenWidth(11)),
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              listCourse(
                                imageUrl: provider.thumbnail,
                                title: widget.dataHistoryTransactionModel!
                                    .courses?[0].title,
                                instructor: widget.dataHistoryTransactionModel!
                                    .courses?[0].instructor,
                                price: widget.dataHistoryTransactionModel!
                                    .courses?[0].price,
                                discountPrice: widget
                                    .dataHistoryTransactionModel!
                                    .courses?[0]
                                    .price,
                                totalPrices: 0,
                              ),
                            ],
                          ),
                          Text(
                            'Rincian Pembayaran',
                            style: thirdTextStyle.copyWith(
                              fontSize: getProportionateScreenWidth(13),
                            ),
                          ),
                          SizedBox(height: getProportionateScreenHeight(11)),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                'Metode Pembayaran',
                                style: thirdTextStyle.copyWith(
                                  fontWeight: reguler,
                                  fontSize: getProportionateScreenWidth(10),
                                ),
                              ),
                              buildTextWidget(),
                            ],
                          ),
                          SizedBox(height: getProportionateScreenHeight(10)),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                'Total Harga',
                                style: thirdTextStyle.copyWith(
                                  fontWeight: reguler,
                                  fontSize: getProportionateScreenWidth(10),
                                ),
                              ),
                              Text(
                                'Rp. ${NumberFormat.currency(locale: 'id', symbol: '', decimalDigits: 0).format(double.parse(provider.detailInvoice![0].grossAmount! ?? "0"))}',
                                style: thirdTextStyle.copyWith(
                                    fontSize: getProportionateScreenWidth(11)),
                              ),
                            ],
                          ),
                          SizedBox(height: getProportionateScreenHeight(2)),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                'Potongan Kupon',
                                style: thirdTextStyle.copyWith(
                                  fontWeight: reguler,
                                  fontSize: getProportionateScreenWidth(10),
                                ),
                              ),
                              Text(
                                'Rp. ${NumberFormat.currency(locale: 'id', symbol: '', decimalDigits: 0).format(double.parse("0"))}',
                                style: thirdTextStyle.copyWith(
                                    fontSize: getProportionateScreenWidth(11)),
                              ),
                            ],
                          ),
                          SizedBox(height: getProportionateScreenHeight(10)),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                'Total Bayar',
                                style: thirdTextStyle.copyWith(
                                  fontWeight: reguler,
                                  fontSize: getProportionateScreenWidth(10),
                                ),
                              ),
                              Text(
                                'Rp. ${NumberFormat.currency(locale: 'id', symbol: '', decimalDigits: 0).format(double.parse(provider.detailInvoice![0].grossAmount! ?? "0"))}',
                                style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(13),
                                  fontWeight: semiBold,
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: getProportionateScreenHeight(10)),
                          DefaultButtonPayment(
                            width: double.infinity,
                            height: 37,
                            text: "Lihat Invoice",
                            weight: semiBold,
                            press: () {
                              if (!isButtonPressed) {
                                isButtonPressed = true;
                                if (provider.detailInvoice?[0]
                                            .transactionStatus ==
                                        'settlement' ||
                                    provider.detailInvoice![0]
                                            .transactionStatus ==
                                        'capture') {
                                  Navigator.push(
                                    context,
                                    CustomNavigator(
                                      child: Invoice(
                                        dataHistoryTransactionModel:
                                            widget.dataHistoryTransactionModel,
                                      ),
                                    ),
                                  );
                                } else {
                                  CherryToast.error(
                                    animationDuration: Durations.long1,
                                    toastDuration: Duration(seconds: 2),
                                    title: Text(
                                      "Pembayaran ini belum berhasil",
                                      style: TextStyle(
                                        color: Colors.black,
                                        fontSize: 15,
                                      ),
                                    ),
                                    animationType: AnimationType.fromTop,
                                  ).show(context);
                                }
                                Future.delayed(Duration(seconds: 2), () {
                                  isButtonPressed = false;
                                });
                              }
                            },
                          ),
                          SizedBox(height: getProportionateScreenHeight(10)),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            } else if (provider.state == detailProvs.ResultState.noData) {
              return Center(child: Text(provider.message ?? ''));
            } else if (provider.state == detailProvs.ResultState.error) {
              return Center(child: Text(provider.message ?? ''));
            } else {
              return Container();
            }
          },
        ),
      ),
    );
  }

  Widget listCourse({
    String? imageUrl,
    String? title,
    String? instructor,
    String? price,
    String? discountPrice,
    int? totalPrices,
  }) {
    return Container(
      padding: EdgeInsets.only(
        top: getProportionateScreenHeight(6),
        bottom: getProportionateScreenHeight(12),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Container(
            width: getProportionateScreenWidth(60),
            height: getProportionateScreenHeight(30),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2),
              image: DecorationImage(
                image: NetworkImage(imageUrl == null || imageUrl.isEmpty
                    ? '$baseUrl/images/default-thumbnail.png'
                    : imageUrl.startsWith("http")
                        ? imageUrl
                        : '$baseUrl/uploads/thumbnail/course_thumbnails/$imageUrl'),
                fit: BoxFit.cover,
              ),
            ),
          ),
          SizedBox(width: getProportionateScreenWidth(10)),
          Flexible(
            flex: 7,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title!,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: thirdTextStyle.copyWith(
                    letterSpacing: 0.5,
                    fontWeight: reguler,
                    fontSize: getProportionateScreenWidth(11),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _statusLabel(String text, Color color) {
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(
          vertical: getProportionateScreenHeight(2),
          horizontal: getProportionateScreenWidth(5)),
      child: Text(
        text,
        style: thirdTextStyle.copyWith(
          color: baruTextutih,
          fontSize: getProportionateScreenWidth(9),
          fontWeight: semiBold,
        ),
      ),
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(5),
      ),
    );
  }
}
