import 'package:cached_network_image/cached_network_image.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/theme_provider.dart';
import 'package:initial_folder/screens/checkout/snap_payment_page.dart';
import 'package:initial_folder/services/history_transactions_service.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:shimmer/shimmer.dart';

class RiwayatList extends StatelessWidget {
  RiwayatList({Key? key, required this.dataHistoryTransactionModel})
      : super(key: key);
  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',
    '-3': 'Dibatalkan',
    '-5': 'Belum Pilih Metode Pembayaran',
  };

  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',
    'qris': 'QRIS'
  };

  Widget _statusLabel(String text, Color color) {
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(
          vertical: getProportionateScreenHeight(4),
          horizontal: getProportionateScreenWidth(5)),
      child: Text(
        text,
        style: thirdTextStyle.copyWith(
          color: baruTextutih,
          fontSize: getProportionateScreenWidth(9),
          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.isEmpty
                      ? '$baseUrl/images/default-thumbnail.png'
                      : thumbnail.startsWith("http")
                          ? thumbnail
                          : '$baseUrl/uploads/thumbnail/course_thumbnails/$thumbnail',
                  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(
                            'https://api.vokasia.id/images/default-thumbnail.png'),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          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) {
    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: getProportionateScreenWidth(16),
              left: getProportionateScreenWidth(8),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  // Order ID
                  dataHistoryTransactionModel.orderId ?? '',
                  style: thirdTextStyle.copyWith(
                    fontWeight: reguler,
                    fontSize: getProportionateScreenWidth(11),
                  ),
                ),
                Row(
                  children: [
                    Text(
                      dataHistoryTransactionModel.date != null
                          ? DateFormat.MMMMEEEEd()
                              .format(dataHistoryTransactionModel.date!)
                          : '',
                      style: thirdTextStyle.copyWith(
                        color: secondaryColor,
                        fontWeight: reguler,
                        fontSize: getProportionateScreenWidth(11),
                      ),
                    ),
                    SizedBox(width: getProportionateScreenWidth(12)),
                    if (dataHistoryTransactionModel.statusPayment != null &&
                        (dataHistoryTransactionModel.statusPayment == '1' ||
                            dataHistoryTransactionModel.statusPayment == '0'))
                      _statusLabel(
                          status[dataHistoryTransactionModel.statusPayment]! ??
                              '',
                          eightColor)
                    else if (dataHistoryTransactionModel.statusPayment == '2' ||
                        dataHistoryTransactionModel.statusPayment == '0')
                      _statusLabel(
                          status[dataHistoryTransactionModel.statusPayment]! ??
                              '',
                          fiveColor)
                    else if (dataHistoryTransactionModel.statusPayment !=
                            null &&
                        status.containsKey(
                            dataHistoryTransactionModel.statusPayment))
                      _statusLabel(
                          status[dataHistoryTransactionModel.statusPayment]!,
                          sevenColor)
                    else
                      _statusLabel("${status['null']}", sevenColor)
                  ],
                ),
              ],
            ),
          ),
          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,
                  ),
                ),
                SizedBox(height: 8),
                Column(
                  children: dataHistoryTransactionModel.courses != null
                      ? dataHistoryTransactionModel.courses!
                          .map((course) =>
                              _listCourse(course.thumbnail, course.title))
                          .toList()
                      : [],
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(
              top: getProportionateScreenHeight(7),
              left: getProportionateScreenWidth(12),
              right: getProportionateScreenWidth(20),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      "Jenis Pembayaran",
                      style: thirdTextStyle.copyWith(
                        fontWeight: reguler,
                        fontSize: getProportionateScreenWidth(11),
                      ),
                    ),
                    Spacer(),
                    Text(
                      dataHistoryTransactionModel.paymentDetail != null &&
                              dataHistoryTransactionModel
                                      .paymentDetail!.paymentType !=
                                  null &&
                              paymentType.containsKey(dataHistoryTransactionModel
                                  .paymentDetail!.paymentType)
                          ? paymentType[dataHistoryTransactionModel
                                  .paymentDetail!.paymentType]!
                              .toUpperCase()
                          : 'Belum Memilih',
                      style: thirdTextStyle.copyWith(
                        fontWeight: reguler,
                        fontSize: getProportionateScreenWidth(11),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: getProportionateScreenHeight(5)),
                Row(
                  children: [
                    Text(
                      "Total Pembelian",
                      style: thirdTextStyle.copyWith(
                        fontWeight: reguler,
                        fontSize: getProportionateScreenWidth(11),
                      ),
                    ),
                    Spacer(),
                    Text(
                      "Rp. ${dataHistoryTransactionModel.paymentDetail?.paymentType != "Coupon Free Course" ? dataHistoryTransactionModel.totalPrice?.toString() ?? '' : "0"}",
                      style: thirdTextStyle.copyWith(
                        fontWeight: bold,
                        color: themeProvider.themeData == ThemeClass.darkmode
                              ?primaryColor : primaryColorligtmode,
                        fontSize: getProportionateScreenWidth(12),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 15),
                dataHistoryTransactionModel.statusPayment == '1' &&
                        dataHistoryTransactionModel
                                .paymentDetail!.paymentType !=
                            'free'
                    ? Column(
                        children: [
                          _customButton(text: 'Receipt'),
                          SizedBox(
                            height: getProportionateScreenHeight(10),
                          ),
                          // _customButton(text: 'Invoice'),
                          // SizedBox(
                          //   height: getProportionateScreenHeight(20),
                          // ),
                        ],
                      )
                    : dataHistoryTransactionModel.statusPayment == '-5'
                        ? Padding(
                          padding: const EdgeInsets.only(top: 10, bottom: 15),
                          child: Column(
                            children: [
                              InkWell(
                                onTap: () async {
                                  showDialog(
                                    context: context,
                                    barrierDismissible: false,
                                    builder: (context) => Center(
                                      child: CircularProgressIndicator(),
                                    ),
                                  );

                                  try {
                                    String orderId = dataHistoryTransactionModel.orderId ?? '';
                                    await HistoryTransactionService().checkTransactionExpiration(orderId);
                                    Navigator.of(context).pop();
                                  } catch (e) {
                                    Navigator.of(context).pop();
                                    print('Error saat memeriksa status transaksi: $e');
                                  }
                                  var redirectUrl = dataHistoryTransactionModel.token;
                                  if (redirectUrl != null && redirectUrl.isNotEmpty) {
                                    Navigator.of(context).push(
                                      MaterialPageRoute(
                                        builder: (context) => SnapPaymentPage(
                                          transactionToken: redirectUrl,
                                          orderId: dataHistoryTransactionModel.orderId ?? '',
                                          grossAmount: dataHistoryTransactionModel.totalPrice ?? 0,
                                          courseTitle: '',
                                          courseThumbnail: '',
                                          courseInstructor: '',
                                          courseId: '',
                                        ),
                                      ),
                                    );
                                  } else {
                                    print("Pembayaran belum dimulai atau URL pembayaran tidak ada.");
                                  }
                                },
                                child: Container(
                                  width: double.infinity,
                                  padding: EdgeInsets.symmetric(vertical: 15),
                                  child: Center(
                                    child: Text(
                                      'Lanjutkan Pembayaran',
                                      style: thirdTextStyle.copyWith(
                                        fontSize: 12,
                                        fontWeight: semiBold,
                                        color: Colors.white,
                                      ),
                                    ),
                                  ),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(5),
                                    color: themeProvider.themeData == ThemeClass.darkmode
                              ?primaryColor : primaryColorligtmode,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        )
                        : Container()
              ],
            ),
          ),
        ],
      ),
    );
  }
}
