import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:initial_folder/base_service.dart';
import 'package:initial_folder/models/history_transaction_model.dart';
import 'package:initial_folder/providers/detail_invoice_provider.dart';
import 'package:initial_folder/providers/order_provider.dart';
import 'package:initial_folder/providers/theme_provider.dart';
import 'package:initial_folder/providers/total_price_provider.dart';
import 'package:initial_folder/screens/checkout/batas_bayar.dart';
import 'package:initial_folder/screens/checkout/gopay/batas_bayar_gopay.dart';
import 'package:initial_folder/screens/profile/account_sign_in/detail_transaksi.dart';
import 'package:initial_folder/services/cancel_payment_service.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:shimmer/shimmer.dart';

import '../screens/checkout/snap_payment_page.dart';

class RiwayatListDelete extends StatefulWidget {
  RiwayatListDelete({
    Key? key,
    required this.dataHistoryTransactionModel,
    required this.onPaymentCancelled,
  }) : super(key: key);
  final HistoryTransactionModel dataHistoryTransactionModel;
  final Function(String) onPaymentCancelled;

  @override
  State<RiwayatListDelete> createState() => _RiwayatListDeleteState();
}

class _RiwayatListDeleteState extends State<RiwayatListDelete> {
  bool isLoading = false;

  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': "Kartu Kredit",
    'credit card': 'Kartu Kredit',
    'qris': 'QRIS',
    'free': 'Kursus Gratis'
  };

  final Map<String, String> bank = {
    'null': "Kartu Kredit",
    'bni': 'BNI Virtual Account',
    'bca': 'BCA Virtual Account',
    'Mandiri': 'Mandiri Virtual Account',
    'Permata': 'Permata Virtual Account',
    'qris': 'QR Code',
    'free': 'Kursus Gratis'
  };

  final Map<String, String> store = {
    'null': "Kartu Kredit",
    'indomaret': 'Indomaret',
    'alfamart': 'Alfamart',
    'free': 'Kursus Gratis'
  };

  Widget _statusLabel(String text, Color color) {
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(
          vertical: getProportionateScreenHeight(5),
          horizontal: getProportionateScreenWidth(5)),
      child: Text(
        text,
        style: primaryTextStyle.copyWith(
            letterSpacing: 0.5,
            color: backgroundColor,
            fontSize: SizeConfig.blockHorizontal! * 2.5,
            fontWeight: semiBold),
      ),
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(5),
      ),
    );
  }

  Widget _customButton({VoidCallback? onTap, String? text}) {
    return InkWell(
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(
            border: Border.all(color: Color.fromARGB(120, 18, 140, 126)),
            borderRadius: BorderRadius.circular(5)),
        padding: EdgeInsets.symmetric(vertical: 15),
        child: Center(
            child: Text(
          text!,
          style: thirdTextStyle.copyWith(
              fontWeight: semiBold, fontSize: 12, letterSpacing: 0.32),
        )),
      ),
      onTap: onTap,
    );
  }

  Widget _listCourse(String? thumbnail, String? title) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Flexible(
              flex: 34,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  CachedNetworkImage(
                    imageUrl: thumbnail != null && thumbnail.isNotEmpty
                        ? '$baseUrl/uploads/thumbnail/course_thumbnails/$thumbnail'
                        : '$baseUrl/images/default-thumbnail.png',
                    imageBuilder: (context, imageProvider) => Container(
                      width: getProportionateScreenWidth(100),
                      height: getProportionateScreenWidth(43),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(5),
                        image: DecorationImage(
                          fit: BoxFit.cover,
                          image: imageProvider,
                        ),
                      ),
                    ),
                    placeholder: (context, url) => Shimmer(
                        child: Container(
                          color: thirdColor,
                        ),
                        gradient: LinearGradient(stops: [
                          0.4,
                          0.5,
                          0.6
                        ], colors: [
                          secondaryColor,
                          thirdColor,
                          secondaryColor
                        ])),
                    errorWidget: (context, url, error) => Container(
                      width: getProportionateScreenWidth(108),
                      height: getProportionateScreenWidth(50),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(5),
                        image: DecorationImage(
                            fit: BoxFit.cover,
                            image: NetworkImage(
                              thumbnail == null || thumbnail.isEmpty
                                  ? '$baseUrl/images/default-thumbnail.png'
                                  : thumbnail.startsWith("http")
                                      ? thumbnail
                                      : '$baseUrl/uploads/thumbnail/course_thumbnails/$thumbnail',
                            )),
                      ),
                    ),
                  ),
                ],
              )),
          SizedBox(width: getProportionateScreenWidth(10)),
          Flexible(
            flex: 96,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  title ?? ' ',
                  style: thirdTextStyle.copyWith(
                    fontWeight: reguler,
                    fontSize: getProportionateScreenWidth(11),
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    var selected = Provider.of<TotalPriceProvider>(context);
    var selectedInvoice = Provider.of<DetailInvoiceProvider>(context);
     final themeProvider = Provider.of<ThemeProvider>(context);

    return Container(
      margin: EdgeInsets.only(
          bottom: getProportionateScreenWidth(10),
          left: getProportionateScreenWidth(16),
          right: getProportionateScreenWidth(16)),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.primaryContainer,
        borderRadius: BorderRadius.circular(4),
        boxShadow: [
          BoxShadow(
            color: Theme.of(context).brightness == Brightness.dark
                ? Colors.transparent
                : secondaryColor.withOpacity(0.5),
            offset: Offset(0, 2),
            blurRadius: 2,
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(
              top: getProportionateScreenHeight(9),
              left: getProportionateScreenWidth(9),
              right: getProportionateScreenWidth(9),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "${widget.dataHistoryTransactionModel.orderId!}",
                      style: thirdTextStyle.copyWith(
                        fontWeight: reguler,
                        fontSize: getProportionateScreenWidth(11),
                      ),
                    ),
                    Text(
                      "Bayar Sebelum",
                      style: thirdTextStyle.copyWith(
                        fontWeight: reguler,
                        fontSize: getProportionateScreenWidth(11),
                        color: secondaryColor,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: getProportionateScreenHeight(5)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      DateFormat('dd MMMM yyyy')
                          .format(widget.dataHistoryTransactionModel.date!),
                      style: thirdTextStyle.copyWith(
                        fontWeight: reguler,
                        fontSize: getProportionateScreenWidth(11),
                        fontFamily: "Poppins",
                      ),
                    ),
                    SizedBox(width: getProportionateScreenWidth(8)),
                    Container(
                      decoration: BoxDecoration(
                        color: sevenColor,
                        borderRadius: BorderRadius.circular(4),
                      ),
                      padding: EdgeInsets.symmetric(
                        horizontal: getProportionateScreenWidth(3),
                        vertical: getProportionateScreenHeight(1),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Icon(
                            Icons.access_time,
                            size: getProportionateScreenWidth(14),
                            color: baruTextutih,
                          ),
                          SizedBox(width: getProportionateScreenWidth(2)),
                          Text(
                            DateFormat('dd MMMM HH:mm').format(widget
                                .dataHistoryTransactionModel.date!
                                .add(Duration(days: 1))),
                            style: thirdTextStyle.copyWith(
                              fontWeight: semiBold,
                              fontSize: getProportionateScreenWidth(11),
                              color: baruTextutih,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.symmetric(
                horizontal: getProportionateScreenWidth(8)),
          ),
          Container(
            margin: EdgeInsets.only(
              top: getProportionateScreenWidth(12),
              left: getProportionateScreenWidth(8),
              right: getProportionateScreenWidth(12),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "Kursus",
                  style: primaryTextStyle.copyWith(
                    fontWeight: reguler,
                    fontSize: getProportionateScreenWidth(12),
                    letterSpacing: 0.5,
                  ),
                ),
                Column(
                  children: widget.dataHistoryTransactionModel.courses!
                      .map((course) =>
                          _listCourse(course.thumbnail, course.title))
                      .toList(),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.symmetric(
                horizontal: getProportionateScreenWidth(10),
                vertical: getProportionateScreenHeight(10)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
      if (widget.dataHistoryTransactionModel.paymentDetail?.paymentType != 'qris') ...[
        Row(
          children: [
            Text(
              "Metode Pembayaran",
              style: primaryTextStyle.copyWith(
                fontFamily: "Poppins",
                fontSize: getProportionateScreenWidth(11),
              ),
            ),
            Spacer(),
            Text(
              widget.dataHistoryTransactionModel.paymentDetail != null &&
                      bank.containsKey(widget.dataHistoryTransactionModel.paymentDetail!.bank)
                  ? toBeginningOfSentenceCase(bank[widget.dataHistoryTransactionModel.paymentDetail!.bank] ?? '') ?? ''
                  : (store.containsKey(widget.dataHistoryTransactionModel.paymentDetail!.store)
                      ? toBeginningOfSentenceCase(store[widget.dataHistoryTransactionModel.paymentDetail!.store] ?? '') ?? ''
                      : toBeginningOfSentenceCase(paymentType[widget.dataHistoryTransactionModel.paymentDetail!.paymentType] ?? '') ?? ''),
              style: primaryTextStyle.copyWith(
                fontWeight: reguler,
                fontSize: getProportionateScreenWidth(11),
              ),
            ),
          ],
        ),
        SizedBox(height: 8),
        Row(
          children: [
            Text(
              widget.dataHistoryTransactionModel.paymentDetail != null &&
                      bank.containsKey(widget.dataHistoryTransactionModel.paymentDetail!.bank)
                  ? "Nomor Virtual Account"
                  : "Kode Pembayaran",
              style: primaryTextStyle.copyWith(
                fontFamily: "Poppins",
                fontSize: getProportionateScreenWidth(11),
              ),
            ),
            Spacer(),
            if (widget.dataHistoryTransactionModel.paymentDetail?.paymentType != 'qris')
              Text(
                widget.dataHistoryTransactionModel.paymentDetail != null
                    ? widget.dataHistoryTransactionModel.paymentDetail!.vaNumber ?? 'QRIS'
                    : 'QRIS',
                style: thirdTextStyle.copyWith(
                  fontWeight: reguler,
                  fontSize: getProportionateScreenWidth(11),
                ),
              ),
          ],
        ),
        SizedBox(height: getProportionateScreenHeight(10)),
      ],
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            "Total Pembayaran",
            style: thirdTextStyle.copyWith(
              fontFamily: "Poppins",
              fontSize: getProportionateScreenWidth(11),
            ),
          ),
          Spacer(),
          Text(
           "Rp. ${widget.dataHistoryTransactionModel.totalPrice! < 50000 ? (widget.dataHistoryTransactionModel.totalPrice! + 5000) : widget.dataHistoryTransactionModel.totalPrice}",
            style: thirdTextStyle.copyWith(
              fontWeight: semiBold,
              fontSize: getProportionateScreenWidth(13),
            ),
          ),
        ],
      ),
      SizedBox(height: getProportionateScreenHeight(10)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    DefaultButtonPayment(
  height: 35,
  width: 150,
  press: () {
    // Cek payment type, jika qris langsung arahkan ke SnapPaymentPage
    if (widget.dataHistoryTransactionModel.paymentDetail?.paymentType == 'qris') {
      var redirectUrl = widget.dataHistoryTransactionModel.token;
      if (redirectUrl != null && redirectUrl.isNotEmpty) {
        Navigator.of(context).push(
          MaterialPageRoute(
            builder: (context) => SnapPaymentPage(
              transactionToken: redirectUrl,
              orderId: widget.dataHistoryTransactionModel.orderId ?? '',
              grossAmount: widget.dataHistoryTransactionModel.totalPrice ?? 0,
              courseTitle: '',
              courseThumbnail: '',
              courseInstructor: '',
              courseId: '',
            ),
          ),
        );
      } else {
        print("Pembayaran belum dimulai atau URL pembayaran tidak ada.");
      }
    } else {
      selected.selectedTotalPrices = widget.dataHistoryTransactionModel.totalPrice ?? 0;
      selectedInvoice.selectedThumbnail = widget.dataHistoryTransactionModel.courses![0].thumbnail;

      Navigator.of(context).push(
        CustomNavigator(
          child: DetailInvoice(
            orderId: widget.dataHistoryTransactionModel.orderId!,
            dataHistoryTransactionModel: widget.dataHistoryTransactionModel,
          ),
        ),
      );
    }
  },
  text: "Bayar Sekarang",
  weight: semiBold,
),

                    SizedBox(
                      width: getProportionateScreenWidth(150),
                      height: getProportionateScreenHeight(32),
                      child: TextButton(
                        onPressed: () async {
                          showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return AlertDialog(
                                elevation: 0.0,
                                backgroundColor:
                                    Theme.of(context).colorScheme.background,
                                contentPadding: EdgeInsets.symmetric(
                                  vertical: getProportionateScreenHeight(20),
                                  horizontal: getProportionateScreenWidth(10),
                                ),
                                actionsPadding: EdgeInsets.only(
                                  right: getProportionateScreenWidth(10),
                                  bottom: getProportionateScreenHeight(12),
                                ),
                                
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(
                                      getProportionateScreenWidth(4)),
                                ),
                                content: Text(
                                    'Apakah Anda yakin ingin membatalkan transaksi?'),
                                actions: [
                                  GestureDetector(
                                    child: Text(
                                      'Ya',
                                      style: TextStyle(
                                        color: primaryColor,
                                        fontSize:
                                            getProportionateScreenWidth(11),
                                      ),
                                    ),
                                    onTap: () async {
                                      Navigator.of(context).pop();
                                      setState(() {
                                        isLoading = true;
                                      });
                                      CancelPaymentService
                                          cancelPaymentService =
                                          CancelPaymentService();
                                      String message =
                                          await cancelPaymentService
                                              .cancelPayment(widget
                                                  .dataHistoryTransactionModel
                                                  .orderId!);
                                      widget.onPaymentCancelled(message);
                                      setState(() {
                                        isLoading = false;
                                      });
                                    },
                                  ),
                                  SizedBox(
                                      width: getProportionateScreenWidth(5)),
                                  GestureDetector(
                                    child: Text(
                                      'Tidak',
                                      style: TextStyle(
                                        color: primaryColor,
                                        fontSize:
                                            getProportionateScreenWidth(11),
                                      ),
                                    ),
                                    onTap: () {
                                      Navigator.of(context).pop();
                                    },
                                  ),
                                ],
                              );
                            },
                          );
                        },
                        child: isLoading
                            ? Container(
                                width: getProportionateScreenWidth(12),
                                height: getProportionateScreenHeight(10),
                                child: CircularProgressIndicator(
                                  color: primaryColor,
                                ),
                              )
                            : Text(
                                "Batalkan Transaksi",
                                style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(12),
                                  fontWeight: semiBold,
                                  color: themeProvider.themeData == ThemeClass.darkmode
                              ?primaryColor : primaryColorligtmode,
                                  letterSpacing: 0.5,
                                ),
                              ),
                        style: TextButton.styleFrom(
                          foregroundColor:
                              Theme.of(context).colorScheme.background,
                          shape: RoundedRectangleBorder(
                            side: BorderSide(color: themeProvider.themeData == ThemeClass.darkmode
                              ?primaryColor : primaryColorligtmode),
                            borderRadius: BorderRadius.circular(
                              getProportionateScreenWidth(5),
                            ),
                          ),
                          backgroundColor: Colors.transparent,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 15),
                widget.dataHistoryTransactionModel.statusPayment == 'Success' &&
                        widget.dataHistoryTransactionModel.paymentDetail!
                                .paymentType !=
                            'free'
                    ? Column(
                        children: [
                          _customButton(text: 'Receipt'),
                          SizedBox(
                            height: getProportionateScreenHeight(10),
                          ),
                          _customButton(text: 'Invoice'),
                          SizedBox(
                            height: getProportionateScreenHeight(20),
                          ),
                        ],
                      )
                    : widget.dataHistoryTransactionModel.statusPayment ==
                            'Pending'
                        ? Padding(
                            padding: const EdgeInsets.only(top: 10, bottom: 15),
                            child: Column(
                              children: [
                                InkWell(
                                  onTap: () {
                                    Navigator.of(context).push(
                                        MaterialPageRoute(
                                            builder: (context) => widget
                                                        .dataHistoryTransactionModel
                                                        .paymentDetail!
                                                        .paymentType ==
                                                    'gopay'
                                                ? BatasBayarGopay()
                                                : BatasBayar(
                                                    historyTransactionModel: widget
                                                        .dataHistoryTransactionModel,
                                                  )));
                                  },
                                  child: Container(
                                    width: double.infinity,
                                    padding: EdgeInsets.symmetric(vertical: 15),
                                    child: Center(
                                        child: Text(
                                      'Detail Pembayaran',
                                      style: thirdTextStyle.copyWith(
                                          fontSize: 12, fontWeight: semiBold),
                                    )),
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(5),
                                        color: primaryColor),
                                  ),
                                ),
                                SizedBox(
                                  height: 10,
                                ),
                                InkWell(
                                  onTap: () {
                                    Provider.of<OrderProvider>(context,
                                            listen: false)
                                        .getTotalPrice(widget
                                            .dataHistoryTransactionModel
                                            .totalPrice
                                            .toString());

                                    Future.wait(widget
                                        .dataHistoryTransactionModel.courses!
                                        .map((course) async {
                                      Provider.of<OrderProvider>(context,
                                              listen: false)
                                          .addOrder(
                                              id: course.courseId,
                                              discountPrice: course.price,
                                              instructor: course.instructor,
                                              price: course.price,
                                              title: course.title,
                                              imageUrl: '');
                                    })).whenComplete(
                                      () => Navigator.of(context).push(
                                        MaterialPageRoute(
                                          builder: (context) => SnapPaymentPage(
                                            orderId: widget
                                                .dataHistoryTransactionModel
                                                .orderId!,
                                            grossAmount: widget
                                                .dataHistoryTransactionModel
                                                .totalPrice!, transactionToken: '', courseTitle: '', courseInstructor: '', courseThumbnail: '', courseId: '',
                                          ),
                                        ),
                                      ),
                                    );
                                  },
                                  child: Container(
                                    width: double.infinity,
                                    padding: EdgeInsets.symmetric(vertical: 15),
                                    child: Center(
                                        child: Text(
                                      'Ubah Metode Pembayaran',
                                      style: thirdTextStyle.copyWith(
                                          fontSize: 12,
                                          fontWeight: semiBold,
                                          color: primaryColor),
                                    )),
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(5),
                                        color: Colors.transparent,
                                        border:
                                            Border.all(color: primaryColor)),
                                  ),
                                ),
                              ],
                            ),
                          )
                        : Container()
              ],
            ),
          ),
        ],
      ),
    );
  }
}
