import 'package:cherry_toast/cherry_toast.dart';
import 'package:cherry_toast/resources/arrays.dart';
import 'package:flutter/material.dart';
import 'package:initial_folder/models/history_transaction_model.dart';
import 'package:initial_folder/providers/detail_invoice_provider.dart';
import 'package:initial_folder/providers/history_transactions_provider.dart'
    as historyProv;
import 'package:initial_folder/providers/page_provider.dart';
import 'package:initial_folder/providers/total_price_provider.dart';
import 'package:initial_folder/screens/home/home_screen.dart';
import 'package:initial_folder/screens/profile/account_sign_in/detail_pembelian_sukses.dart';
import 'package:initial_folder/screens/profile/account_sign_in/riwayat_transaksi_pending.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/custom_navigator_pop.dart';
import 'package:initial_folder/widgets/riwayat_list.dart';
import 'package:provider/provider.dart';
import 'package:shimmer/shimmer.dart';

class RiwayatTransaksi extends StatefulWidget {
  RiwayatTransaksi({Key? key}) : super(key: key);
  static const String routeName = "/riwayat-transaksi";

  @override
  State<RiwayatTransaksi> createState() => _RiwayatTransaksiState();
}

class _RiwayatTransaksiState extends State<RiwayatTransaksi> {
  bool isButtonPressed = false;

   Future<bool> _onWillPop() async {
    Provider.of<PageProvider>(context, listen: false).currentIndex = 4;
    Navigator.pushAndRemoveUntil(
      context,
      CustomNavigatorPop(
        child: HomeScreen(),
      ),
      (route) => false,
    );
    return Future.value(false);
  }

  @override
  void initState() {
    super.initState();
    // Memanggil fungsi getHistoryTransaction untuk refresh data ketika halaman pertama kali dibuka
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Provider.of<historyProv.HistoryTranscationsProvider>(context, listen: false)
          .getHistoryTransaction();
    });
  }

  @override
  Widget build(BuildContext context) {
    var selected = Provider.of<DetailInvoiceProvider>(context);
    var historyProvider =
        Provider.of<historyProv.HistoryTranscationsProvider>(context);
    final selectedTotalPrices = Provider.of<TotalPriceProvider>(context);
    PageProvider pageProvider = Provider.of<PageProvider>(context);

     return WillPopScope(
      onWillPop: _onWillPop,
      child: SafeArea(
        child: Scaffold(
        appBar: AppBar(
          scrolledUnderElevation: 0.0,
          backgroundColor: Theme.of(context).colorScheme.background,
          centerTitle: true,
          title: Text(
            'Riwayat Pembelian',
            style: thirdTextStyle.copyWith(
              fontWeight: semiBold,
              fontSize: getProportionateScreenWidth(15),
            ),
          ),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              color: Theme.of(context).colorScheme.onBackground,
              size: getProportionateScreenWidth(17),
            ),
            onPressed: () {
              _onWillPop();
            },
          ),
        ),
        body: Column(
          children: [
            InkWell(
              onTap: () {
                Navigator.push(
                  context,
                  CustomNavigator(
                    child: RiwayatTransaksiPending(),
                  ),
                );
              },
              child: Container(
                padding: EdgeInsets.symmetric(
                    vertical: getProportionateScreenHeight(12)),
                margin: EdgeInsets.symmetric(
                    vertical: getProportionateScreenHeight(10),
                    horizontal: getProportionateScreenWidth(16)),
                decoration: BoxDecoration(
                  color: Theme.of(context).brightness == Brightness.dark
                      ? seventeenColor.withOpacity(0.3)
                      : baruTextutih,
                  borderRadius: BorderRadius.circular(5),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Row(
                      children: [
                        Icon(
                          Icons.pending_actions,
                          color: Theme.of(context).brightness == Brightness.dark
                              ? secondaryColor
                              : baruTexthitam,
                          size: getProportionateScreenWidth(17),
                        ),
                        SizedBox(width: getProportionateScreenWidth(15)),
                        Text(
                          'Menunggu Pembayaran  (${historyProvider.paymentPending?.length ?? 0})',
                          style: thirdTextStyle.copyWith(
                            fontSize: getProportionateScreenWidth(15),
                            color:
                                Theme.of(context).brightness == Brightness.dark
                                    ? secondaryColor
                                    : baruTexthitam,
                          ),
                        )
                      ],
                    ),
                    Icon(Icons.chevron_right)
                  ],
                ),
              ),
            ),
            Consumer<historyProv.HistoryTranscationsProvider>(
              builder: (context, state, _) {
                if (state.state == historyProv.ResultState.loading) {
                  return Padding(
                    padding: EdgeInsets.symmetric(
                        horizontal: getProportionateScreenWidth(15)),
                    child: Shimmer.fromColors(
                      baseColor: Colors.white,
                      highlightColor: Colors.grey,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Container(
                            width: double.infinity,
                            height: getProportionateScreenHeight(90),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8),
                              color: Colors.white,
                            ),
                          ),
                          SizedBox(height: getProportionateScreenHeight(8)),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Container(
                                width: getProportionateScreenWidth(100),
                                height: getProportionateScreenHeight(15),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: getProportionateScreenHeight(8)),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                width: getProportionateScreenWidth(130),
                                height: getProportionateScreenHeight(70),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                  color: Colors.white,
                                ),
                              ),
                              SizedBox(width: getProportionateScreenWidth(10)),
                              Container(
                                width: getProportionateScreenWidth(130),
                                height: getProportionateScreenHeight(15),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: getProportionateScreenHeight(8)),
                          Container(
                            width: double.infinity,
                            height: getProportionateScreenHeight(90),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8),
                              color: Colors.white,
                            ),
                          ),
                          SizedBox(height: getProportionateScreenHeight(15)),
                          Container(
                            width: double.infinity,
                            height: getProportionateScreenHeight(90),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8),
                              color: Colors.white,
                            ),
                          ),
                          SizedBox(height: getProportionateScreenHeight(8)),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Container(
                                width: getProportionateScreenWidth(100),
                                height: getProportionateScreenHeight(15),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: getProportionateScreenHeight(8)),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                width: getProportionateScreenWidth(130),
                                height: getProportionateScreenHeight(70),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                  color: Colors.white,
                                ),
                              ),
                              SizedBox(width: getProportionateScreenWidth(10)),
                              Container(
                                width: getProportionateScreenWidth(130),
                                height: getProportionateScreenHeight(15),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: getProportionateScreenHeight(8)),
                          Container(
                            width: double.infinity,
                            height: getProportionateScreenHeight(90),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8),
                              color: Colors.white,
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                } else if (state.state == historyProv.ResultState.noData) {
                  return Center(
                    child: Text(state.message),
                  );
                } else if (state.state == historyProv.ResultState.hasData) {
                  List<HistoryTransactionModel> history = state.historyPayment!;
                  return Expanded(
                    child: RefreshIndicator(
                      onRefresh: () async {
                        await Provider.of<
                                    historyProv.HistoryTranscationsProvider>(
                                context,
                                listen: false)
                            .getHistoryTransaction();
                      },
                      color: primaryColor,
                      strokeWidth: 2,
                      child: ListView.builder(
                       
                        physics: ScrollPhysics(),
                        itemCount: history.length,
                        itemBuilder: (context, index) {
                          return GestureDetector(
                            onTap: () {
                              selectedTotalPrices.selectedTotalPrices = history[index].totalPrice ?? 0;
                              selected.selectedThumbnail = history[index].courses?.isNotEmpty == true 
                                  ? history[index].courses![0].thumbnail ?? 'default_thumbnail.png' 
                                  : 'default_thumbnail.png';
                              if (!isButtonPressed) {
                                setState(() {
                                  isButtonPressed = true;
                                });
                                if (history[index].statusPayment != "0") {
                                  Navigator.push(
                                    context,
                                    CustomNavigator(
                                      child: DetailPembelianSukses(
                                        orderId: history[index].orderId!,
                                        dataHistoryTransactionModel:
                                            history[index],
                                      ),
                                    ),
                                  );
                                } else {
                                  CherryToast.error(
                                    animationDuration: Durations.medium1,
                                    toastDuration: Duration(seconds: 2),
                                    title: Text(
                                      "Pembayaran gratis tidak memiliki invoice",
                                      style: TextStyle(
                                        color: Colors.black,
                                        fontSize: 15,
                                      ),
                                    ),
                                    animationType: AnimationType.fromTop,
                                  ).show(context);
                                }
                                Future.delayed(Duration(seconds: 2), () {
                                  isButtonPressed = false;
                                });
                              }
                            },
                            child: RiwayatList(
                              dataHistoryTransactionModel: history[index],
                            ),
                          );
                        },
                      ),
                    ),
                  );
                } else if (state.state == historyProv.ResultState.error) {
                  return RefreshIndicator(
                    onRefresh: () async {
                      await Provider.of<
                                  historyProv.HistoryTranscationsProvider>(
                              context,
                              listen: false)
                          .getHistoryTransaction();
                    },
                    child: Center(
                      child: Text(state.message),
                    ),
                  );
                } else {
                  return Center(
                    child: CircularProgressIndicator(
                      color: primaryColor,
                      strokeWidth: 2,
                    ),
                  );
                }
              },
            ),
          ],
        ),
      ),),
    );


  }
}
