// ignore_for_file: must_be_immutable

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:frezka/components/cached_image_widget.dart';
import 'package:frezka/paymentGateways/models/payment_list_model.dart';
import 'package:frezka/paymentGateways/services/razor_pay_service.dart';
import 'package:frezka/utils/colors.dart';
import 'package:nb_utils/nb_utils.dart';
import '../../components/app_scaffold.dart';
import '../../components/price_widget.dart';
import '../../main.dart';
import '../../network/rest_apis.dart';
import '../../paymentGateways/models/payment_gateway_response.dart';
import '../../paymentGateways/services/stripe_service.dart';
import '../../utils/app_common.dart';
import '../../utils/constants.dart';
import '../../utils/images.dart';

class UserWalletBalanceScreen extends StatefulWidget {
  bool isBackScreen;

  UserWalletBalanceScreen({Key? key, this.isBackScreen = false}) : super(key: key);

  @override
  State<UserWalletBalanceScreen> createState() => _UserWalletBalanceScreenState();
}

class _UserWalletBalanceScreenState extends State<UserWalletBalanceScreen> {
  Future<List<PaymentSetting>>? future;
  TextEditingController tipController = TextEditingController();
  TextEditingController walletAmountCont = TextEditingController(text: '0');
  FocusNode walletAmountFocus = FocusNode();

  List<int> defaultAmounts = [150, 200, 500, 1000, 5000, 10000];
  PaymentSetting? currentPaymentMethod;

  List<PaymentData> payments = getPaymentList(includeWallet: false, includeCash: true);
  PaymentData selectedPayment = PaymentData();
  RazorPayService razorPayService = RazorPayService();
  StripeService stripeServices = StripeService();

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

  void init() async {
    appStore.setUserWalletAmount();
  }

  void _handleClick() async {
    log("${walletAmountCont.text}");
    if (walletAmountCont.text.toDouble() == 0) {
      return toast("Please Enter the Amount.");
    } else if (selectedPayment.paymentMethod == null) {
      return toast("Please select payment method");
    }

    log("${selectedPayment.paymentMethod!}");
    log("${locale.PAYMENT_METHOD_CASH}");

    if (selectedPayment.paymentMethod! == locale.PAYMENT_METHOD_STRIPE) {
      await stripeServices.init(
        totalAmount: walletAmountCont.text.toDouble(),
        isTest: true,
        onComplete: (res) {
          finish(context);
          finish(context);
          Map req = {"amount": walletAmountCont.text.toDouble(), "transaction_type": PaymentMethods.PAYMENT_METHOD_STRIPE, "transaction_id": res['transaction_id']};
          walletTopUpApi(request: req);
          walletAmountCont.text = "0.0";
        },
      );

      await 1.seconds.delay;
      stripeServices.stripePay().then((value) {
        appStore.setLoading(false);
      }).catchError((e) {
        appStore.setLoading(false);
        toast(e.toString());
      });
    } else if (selectedPayment.paymentMethod! == locale.PAYMENT_METHOD_RAZORPAY) {
      appStore.currencyCode = 'INR';
      razorPayService.init(
        razorKey: getStringAsync(PaymentKeys.RAZORPAY_PUBLIC_KEY),
        totalAmount: walletAmountCont.text.toDouble(),
        onComplete: (res) async {
          log(res);
          Map req = {"amount": walletAmountCont.text.toDouble(), "transaction_type": PaymentMethods.PAYMENT_METHOD_RAZORPAY, "transaction_id": res['paymentId']};
          await walletTopUpApi(request: req);
          walletAmountCont.text = "0.0";
        },
      );

      await 1.seconds.delay;
      appStore.setLoading(false);

      razorPayService.razorPayCheckout();
    } else if (selectedPayment.paymentMethod! == locale.PAYMENT_METHOD_CASH) {
      var id = "C" + Random().nextInt(100000).toString();
      Map req = {"amount": walletAmountCont.text.toDouble(), "transaction_type": PaymentMethods.PAYMENT_METHOD_CASH, "transaction_id": id};
      walletTopUpApi(request: req);
      walletAmountCont.text="0.0";
    }
  }

  String getPaymentMethodIcon(String value) {
    if (value == PaymentMethods.PAYMENT_METHOD_STRIPE) {
      return stripe_logo;
    } else if (value == PaymentMethods.PAYMENT_METHOD_RAZORPAY) {
      return razorpay_logo;
    } else if (value == PaymentMethods.CINET) {
      // return cinetpay_logo;
    } else if (value == PaymentMethods.PAYMENT_METHOD_FLUTTER_WAVE) {
      return flutter_wave_logo;
    } else if (value == PaymentMethods.PAYMENT_METHOD_SADAD_PAYMENT) {
      return "";
    } else if (value == PaymentMethods.PAYMENT_METHOD_PAYPAL) {
      return paypal_logo;
    } else if (value == PaymentMethods.AIRTEL_MONEY) {
      // return airtel_logo;
    } else if (value == PaymentMethods.PAYMENT_METHOD_PAYSTACK) {
      return paystack_logo;
    } else if (value == PaymentMethods.PAYMENT_METHOD_PHONEPE) {
      // return phonepe_logo;
    }

    return '';
  }

  walletTopUpApi({required Map request}) {
    walletTopUp(request).then((value) {
      if (widget.isBackScreen) {
        finish(context, true);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      appBarWidget: commonAppBarWidget(
        context,
        title: locale.myWallet,
        appBarHeight: 70,
        roundCornerShape: true,
        showLeadingIcon: true,
      ),
      body: Stack(
        children: [
          AnimatedScrollView(
            physics: AlwaysScrollableScrollPhysics(),
            listAnimationType: ListAnimationType.None,
            onSwipeRefresh: () {
              appStore.setUserWalletAmount();

              return 1.seconds.delay;
            },
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  12.height,
                  Container(
                    width: context.width(),
                    padding: EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey.withValues(alpha:0.1),
                          spreadRadius: 1,
                          blurRadius: 4,
                          offset: Offset(0, 1),
                        ),
                      ],
                    ),
                    child: Row(
                      children: [
                        Text(locale.balance, style: primaryTextStyle()).expand(),
                        Observer(builder: (context) => PriceWidget(price: appStore.userWalletAmount, size: 16, isBoldText: true, color: Colors.green)),
                      ],
                    ),
                  ).paddingSymmetric(horizontal: 12),
                  12.height,
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      16.height,
                      Text(locale.topUpWallet, style: boldTextStyle(size: LABEL_TEXT_SIZE)),
                      8.height,
                      Text(locale.topUpAmountQuestion, style: secondaryTextStyle()),
                      Container(
                        width: context.width(),
                        margin: EdgeInsets.symmetric(vertical: 16),
                        padding: EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.grey.withValues(alpha:0.1),
                              spreadRadius: 1,
                              blurRadius: 4,
                              offset: Offset(0, 1),
                            ),
                          ],
                        ),
                        child: Column(
                          children: [
                            AppTextField(
                              textFieldType: TextFieldType.NUMBER,
                              //textAlign: TextAlign.center,
                              controller: walletAmountCont,
                              focus: walletAmountFocus,
                              textStyle: primaryTextStyle(size: 25, weight: FontWeight.bold),
                              inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                              onTap: () {
                                if (walletAmountCont.text == '0') {
                                  walletAmountCont.selection = TextSelection(baseOffset: 0, extentOffset: walletAmountCont.text.length);
                                }
                              },
                              decoration: InputDecoration(
                                prefixText: isCurrencyPositionLeft ? appStore.currencySymbol + " " : '',
                                prefixStyle: boldTextStyle(size: 25),
                                suffixText: isCurrencyPositionRight ? appStore.currencySymbol + " " : '',
                                suffixStyle: boldTextStyle(size: 25),
                              ),
                              onChanged: (p0) {
                                //
                              },
                            ),
                            24.height,
                            Wrap(
                              spacing: 20,
                              runSpacing: 12,
                              alignment: WrapAlignment.center,
                              children: List.generate(defaultAmounts.length, (index) {
                                return Container(
                                  padding: EdgeInsets.symmetric(vertical: 6, horizontal: 12),
                                  decoration: boxDecorationDefault(
                                    color: defaultAmounts[index].toString() == walletAmountCont.text ? white : secondaryColor,
                                    borderRadius: radius(8),
                                    border: Border.all(color: defaultAmounts[index].toString() == walletAmountCont.text ? context.primaryColor : Colors.white12),
                                  ),
                                  child: Text(
                                    defaultAmounts[index].toString().formatNumberWithComma(),
                                    style: primaryTextStyle(color: defaultAmounts[index].toString() == walletAmountCont.text ? context.primaryColor : Colors.white),
                                  ),
                                ).onTap(() {
                                  walletAmountCont.text = "${defaultAmounts[index].toString()}";
                                  setState(() {});
                                });
                              }),
                            ),
                          ],
                        ),
                      ),
                      16.height,
                      Text(locale.paymentMethod, style: boldTextStyle(size: LABEL_TEXT_SIZE)),
                      4.height,
                      Text(locale.selectYourPaymentMethodToAddBalance, style: secondaryTextStyle()),
                      8.height,
                      ListView.builder(
                        shrinkWrap: true,
                        itemCount: payments.length,
                        physics: NeverScrollableScrollPhysics(),
                        padding: EdgeInsets.zero,
                        itemBuilder: (context, index) {
                          if (payments[index].paymentMethod?.toLowerCase() == PaymentMethods.PAYMENT_METHOD_CASH) {
                            return Offstage();
                          }
                          return Container(
                            width: 300,
                            decoration: boxDecorationWithRoundedCorners(borderRadius: radius(), backgroundColor: context.cardColor),
                            margin: EdgeInsets.only(bottom: 16),
                            child: SettingItemWidget(
                              title: payments[index].paymentMethod.validate(),
                              titleTextStyle: boldTextStyle(size: 14),
                              padding: EdgeInsets.only(left: 16, bottom: 10, top: 10, right: 10),
                              leading: CachedImageWidget(url: payments[index].icon.validate(), height: 22, width: 22, fit: BoxFit.contain),
                              radius: radius(),
                              trailing: Radio<PaymentData>(
                                value: payments[index],
                                visualDensity: VisualDensity.compact,
                                groupValue: selectedPayment,
                                onChanged: (value) {
                                  selectedPayment = value!;

                                  if (index == 0) {
                                    tipController.text = '';
                                    bookingRequestStore.setTip(0);
                                  }
                                  setState(() {});
                                },
                              ),
                              onTap: () {
                                selectedPayment = payments[index];

                                if (index == 0) {
                                  tipController.text = '';
                                  bookingRequestStore.setTip(0);
                                }
                                setState(() {});
                              },
                            ),
                          );
                        },
                      ),
                      100.height,
                    ],
                  ).paddingSymmetric(horizontal: 16),
                ],
              ),
            ],
          ),
          Positioned(
            bottom: 16,
            left: 16,
            right: 16,
            child: AppButton(
              width: context.width(),
              height: 16,
              color: context.primaryColor,
              text: locale.proceedToTopUp,
              textStyle: boldTextStyle(color: white),
              onTap: () async {
                hideKeyboard(context);
                _handleClick();
              },
            ),
          ),
        ],
      ),
    );
  }
}