import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/providers/cart_provider.dart';
import 'package:initial_folder/providers/carts_provider.dart';
import 'package:initial_folder/providers/payments_provider.dart';
import 'package:initial_folder/screens/checkout/components/bottom_sheet_detail.dart';
import 'package:initial_folder/screens/checkout/gopay/payment_instruction_gopay.dart';
import 'package:initial_folder/screens/checkout/gopay/qr_code_gopay.dart';
import 'package:initial_folder/screens/checkout/success_paid_course.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/login_regist/default_button.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:pusher_client/pusher_client.dart';

class BatasBayarGopay extends StatefulWidget {
  final List<String>? idCart;
  BatasBayarGopay({this.idCart});
  @override
  State<BatasBayarGopay> createState() => _BatasBayarGopayState();
}

class _BatasBayarGopayState extends State<BatasBayarGopay> {
  Channel? _channel;
  String? statusTransaction;

  Future<void> deleteCourse() async {
    List<String> idCarts = widget.idCart ?? [];

    idCarts.forEach((element) async {
      await Provider.of<CartProvider>(context, listen: false)
          .deleteCart(element);
      await Provider.of<CartsProvider>(context, listen: false).getCarts();
    });
  }

  Future<void> initPusher() async {
    int? idUser = await UsersInfo().getIdUser();

    PusherClient pusher = PusherClient(
        '92060797e94ac7033edb', PusherOptions(cluster: 'ap1'),
        autoConnect: false);

    pusher.connect();

    // pusher.onConnectionStateChange((state) {
    //   print(state!.currentState);
    // });
    // pusher.onConnectionError((error) {
    //   print(error);
    // });

    _channel = pusher.subscribe('payment-channel');

    _channel!.bind('paid-event-$idUser', (event) {
      if (mounted) {
        final status = jsonDecode(event!.data!);
        setState(() {
          statusTransaction = status['status_code'];
          if (statusTransaction == "201") {
            print(status['message']);
            print(widget.idCart);
            deleteCourse();
            // Navigator.of(context).pushAndRemoveUntil(
            //   MaterialPageRoute(
            //     builder: (context) => SuccessPaidCourse(),
            //   ),
            //   (route) => false,
            // );
          }
        });
      }
    });
  }

  @override
  void initState() {
    initPusher();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var detailOrder = Provider.of<PaymentsProvider>(context).detailOrder;
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Selesaikan Pembayaran',
          style: secondaryTextStyle.copyWith(
              letterSpacing: 1,
              fontWeight: semiBold,
              fontSize: getProportionateScreenWidth(14)),
        ),
      ),
      body: SingleChildScrollView(
        child: Container(
          margin:
              EdgeInsets.symmetric(horizontal: getProportionateScreenWidth(16)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              SizedBox(height: getProportionateScreenHeight(10)),
              Center(
                child: Column(
                  children: [
                    Text(
                      'Batas akhir pembayaran sampai',
                      style: primaryTextStyle.copyWith(
                        color: secondaryColor,
                        letterSpacing: 0.5,
                        fontWeight: reguler,
                        fontSize: getProportionateScreenWidth(10),
                      ),
                    ),
                    SizedBox(height: getProportionateScreenHeight(5)),
                    Text(
                      // 'Rabu, 13 Oktober 2021 (Pukul 19:32)',
                      DateFormat('E, d MMM y (H:m)')
                          .format(detailOrder[0].transactionTimeLimit),
                      style: secondaryTextStyle.copyWith(
                        letterSpacing: 1,
                        fontWeight: semiBold,
                        color: tenthColor,
                        fontSize: SizeConfig.blockHorizontal! * 3,
                      ),
                    ),
                    SizedBox(height: getProportionateScreenHeight(5)),
                    Text(
                      'Segera selesaikan pembayaran atau pesananmu',
                      style: primaryTextStyle.copyWith(
                        color: secondaryColor,
                        letterSpacing: 0.5,
                        fontWeight: reguler,
                        fontSize: getProportionateScreenWidth(10),
                      ),
                    ),
                    Text(
                      'akan dibatalkan secara otomatis',
                      style: primaryTextStyle.copyWith(
                        color: secondaryColor,
                        letterSpacing: 0.5,
                        fontWeight: reguler,
                        fontSize: getProportionateScreenWidth(10),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: getProportionateScreenHeight(30),
              ),
              Container(
                decoration: BoxDecoration(
                  color: Color(0xFF212121),
                  borderRadius: BorderRadius.circular(8),
                ),
                margin: EdgeInsets.only(
                    left: getProportionateScreenWidth(2),
                    right: getProportionateScreenWidth(2)),
                child: Container(
                  padding: EdgeInsets.symmetric(
                      vertical: 16,
                      horizontal: getProportionateScreenWidth(10)),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Metode Pembayaran',
                        style: primaryTextStyle.copyWith(
                          color: Colors.white,
                          letterSpacing: 0.5,
                          fontWeight: reguler,
                          fontSize: getProportionateScreenWidth(10),
                        ),
                      ),
                      SizedBox(
                        height: getProportionateScreenHeight(8),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            'GoPay',
                            style: primaryTextStyle.copyWith(
                              color: Colors.white,
                              letterSpacing: 1,
                              fontWeight: semiBold,
                              fontSize: getProportionateScreenWidth(13),
                            ),
                          ),
                          Container(
                            width: getProportionateScreenWidth(50),
                            height: getProportionateScreenWidth(17),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(2),
                              image: DecorationImage(
                                fit: BoxFit.scaleDown,
                                image: AssetImage('assets/images/gopay2.png'),
                              ),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        height: getProportionateScreenHeight(16),
                      ),
                      Text(
                        'Kode QR',
                        style: primaryTextStyle.copyWith(
                          color: Colors.white,
                          letterSpacing: 0.5,
                          fontWeight: reguler,
                          fontSize: getProportionateScreenWidth(10),
                        ),
                      ),
                      SizedBox(
                        height: getProportionateScreenHeight(8),
                      ),
                      Row(
                        children: [
                          Icon(Icons.qr_code),
                          Spacer(),
                          GestureDetector(
                            onTap: () {
                              // Navigator.push(
                              //     context,
                              //     MaterialPageRoute(
                              //         builder: (context) => QRCodeGopay()));
                              Navigator.pop(context);
                            },
                            child: Text(
                              "Scan Kode QR",
                              style: primaryTextStyle.copyWith(
                                  letterSpacing: 0.5,
                                  color: primaryColor,
                                  fontSize: getProportionateScreenWidth(10),
                                  fontWeight: reguler),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        height: getProportionateScreenHeight(16),
                      ),
                      Text(
                        'Total Pembayaran',
                        style: primaryTextStyle.copyWith(
                          color: Colors.white,
                          letterSpacing: 0.5,
                          fontWeight: reguler,
                          fontSize: getProportionateScreenWidth(10),
                        ),
                      ),
                      SizedBox(
                        height: getProportionateScreenHeight(8),
                      ),
                      Row(
                        children: [
                          Text(
                            'Rp. ${NumberFormat.currency(locale: 'id', symbol: '', decimalDigits: 0).format(double.parse(detailOrder[0].totalPayment))}',
                            style: primaryTextStyle.copyWith(
                              color: Colors.white,
                              letterSpacing: 1,
                              fontWeight: semiBold,
                              fontSize: getProportionateScreenWidth(14),
                            ),
                          ),
                          Spacer(),
                          GestureDetector(
                            onTap: () {
                              showModalBottomSheet(
                                  context: context,
                                  shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.vertical(
                                          top: Radius.circular(20))),
                                  builder: (context) {
                                    return BottomSheetDetail();
                                  });
                            },
                            child: Text(
                              "Detail Pembayaran",
                              style: primaryTextStyle.copyWith(
                                  letterSpacing: 0.5,
                                  color: primaryColor,
                                  fontSize: getProportionateScreenWidth(10),
                                  fontWeight: reguler),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        height: getProportionateScreenHeight(16),
                      ),
                      Text(
                        'Status Pembayaran',
                        style: primaryTextStyle.copyWith(
                          color: Colors.white,
                          letterSpacing: 0.5,
                          fontWeight: reguler,
                          fontSize: getProportionateScreenWidth(10),
                        ),
                      ),
                      SizedBox(
                        height: getProportionateScreenHeight(8),
                      ),
                      Text(
                        statusTransaction == '201' || statusTransaction == null
                            ? 'Pending'
                            : 'Success',
                        style: primaryTextStyle.copyWith(
                          color: Color(0xffEDA923),
                          letterSpacing: 1,
                          fontWeight: medium,
                          fontSize: getProportionateScreenWidth(12),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              SizedBox(
                height: getProportionateScreenHeight(24),
              ),
              DefaultButton(
                text: 'Belanja kursus lainnya',
                weight: reguler,
                press: () {
                  Navigator.pushNamedAndRemoveUntil(
                      context, "/home", (r) => false);
                },
              ),
              SizedBox(
                height: getProportionateScreenHeight(32),
              ),
              Container(
                decoration: BoxDecoration(
                  color: Color(0xFF212121),
                  borderRadius: BorderRadius.circular(8),
                ),
                margin: EdgeInsets.only(
                    left: getProportionateScreenWidth(2),
                    right: getProportionateScreenWidth(2)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      padding: EdgeInsets.symmetric(
                          vertical: 16,
                          horizontal: getProportionateScreenWidth(16)),
                      child: Text(
                        'Cara Pembayaran',
                        style: secondaryTextStyle.copyWith(
                          color: tenthColor,
                          letterSpacing: 1,
                          fontWeight: semiBold,
                          fontSize: getProportionateScreenWidth(14),
                        ),
                      ),
                    ),
                    Divider(
                        color: Color(0xff2D2D2D), thickness: 0.5, height: 0.5),
                    PaymentInstructionGopay()
                  ],
                ),
              ),
              SizedBox(
                height: getProportionateScreenHeight(30),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
