import 'dart:async';
import 'dart:io';

import 'package:hmg_patient_app/core/model/my_balance/tamara_installment_details.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/services/appointment_services/GetDoctorsList.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/buttons/custom_text_button.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';

class PaymentMethod extends StatefulWidget {
  Function onSelectedMethod;
  bool? isShowInstallments;
  num? patientShare;
  bool? isFromAdvancePayment;

  PaymentMethod({required this.onSelectedMethod, this.isShowInstallments = false, this.patientShare, this.isFromAdvancePayment = false});

  @override
  _PaymentMethodState createState() => _PaymentMethodState();
}

class _PaymentMethodState extends State<PaymentMethod> {
  String selectedPaymentMethod = "MADA";
  TamaraInstallmentDetails? tamaraInstallmentDetails;
  String? selectedInstallmentPlan;

  num minTamaraLimit = 0;
  num maxTamaraLimit = 0;

  ProjectViewModel? projectViewModel;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getTamaraPaymentDetails();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).paymentMethod,
      isShowAppBar: true,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      backgroundColor: CustomColors.appBackgroudGrey2Color,
      body: Container(
        margin: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
        child: SingleChildScrollView(
          child: Container(
            child: Column(
              mainAxisSize: MainAxisSize.max,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.fromLTRB(4, 15.0, 4, 0.0),
                  child: Text(TranslationBase.of(context).selectPaymentOption, style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold)),
                ),
                if (projectViewModel!.havePrivilege(86))
                  Container(
                    width: double.infinity,
                    child: InkWell(
                      onTap: () {
                        updateSelectedPaymentMethod("MADA");
                      },
                      child: Card(
                        elevation: 0.0,
                        margin: EdgeInsets.fromLTRB(8.0, 16.0, 8.0, 8.0),
                        color: Colors.white,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                          side: selectedPaymentMethod == "MADA" ? BorderSide(color: Colors.green, width: 2.0) : BorderSide(color: Colors.transparent, width: 0.0),
                        ),
                        child: Padding(
                          padding: const EdgeInsets.all(12.0),
                          child: Row(
                            children: [
                              Container(
                                width: 24,
                                height: 24,
                                decoration: containerColorRadiusBorderWidth(selectedPaymentMethod == "MADA" ? CustomColors.accentColor : Colors.transparent, 100, Colors.grey, 0.5),
                              ),
                              mWidth(12),
                              Container(
                                height: 70.0,
                                width: 70.0,
                                padding: EdgeInsets.all(7.0),
                                child: Image.asset("assets/images/new/payment/Mada.png"),
                              ),
                              mFlex(1),
                              if (selectedPaymentMethod == "MADA")
                                Container(
                                  decoration: containerRadius(CustomColors.green, 200),
                                  padding: EdgeInsets.only(top: 6, bottom: 6, left: 12, right: 12),
                                  child: Text(
                                    TranslationBase.of(context).paymentSelected,
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 11,
                                    ),
                                  ),
                                ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                if (projectViewModel!.havePrivilege(87))
                  Container(
                    width: double.infinity,
                    child: InkWell(
                      onTap: () {
                        updateSelectedPaymentMethod("VISA");
                      },
                      child: Card(
                        elevation: 0.0,
                        margin: EdgeInsets.fromLTRB(8.0, 16.0, 8.0, 8.0),
                        color: Colors.white,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                          side: selectedPaymentMethod == "VISA" ? BorderSide(color: Colors.green, width: 2.0) : BorderSide(color: Colors.transparent, width: 0.0),
                        ),
                        child: Padding(
                          padding: const EdgeInsets.all(12.0),
                          child: Row(
                            children: [
                              Container(
                                width: 24,
                                height: 24,
                                decoration: containerColorRadiusBorderWidth(selectedPaymentMethod == "VISA" ? CustomColors.accentColor : Colors.transparent, 100, Colors.grey, 0.5),
                              ),
                              mWidth(12),
                              Container(
                                height: 60.0,
                                padding: EdgeInsets.all(7.0),
                                width: 60,
                                child: Image.asset("assets/images/new/payment/visa.png"),
                              ),
                              mFlex(1),
                              if (selectedPaymentMethod == "VISA")
                                Container(
                                  decoration: containerRadius(CustomColors.green, 200),
                                  padding: EdgeInsets.only(top: 6, bottom: 6, left: 12, right: 12),
                                  child: Text(
                                    TranslationBase.of(context).paymentSelected,
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 11,
                                    ),
                                  ),
                                ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                if (projectViewModel!.havePrivilege(88))
                  Container(
                    width: double.infinity,
                    child: InkWell(
                      onTap: () {
                        updateSelectedPaymentMethod("MASTERCARD");
                      },
                      child: Card(
                        elevation: 0.0,
                        margin: EdgeInsets.fromLTRB(8.0, 16.0, 8.0, 8.0),
                        color: Colors.white,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                          side: selectedPaymentMethod == "MASTERCARD" ? BorderSide(color: Colors.green, width: 2.0) : BorderSide(color: Colors.transparent, width: 0.0),
                        ),
                        child: Padding(
                          padding: const EdgeInsets.all(12.0),
                          child: Row(
                            children: [
                              Container(
                                width: 24,
                                height: 24,
                                decoration: containerColorRadiusBorderWidth(selectedPaymentMethod == "MASTERCARD" ? CustomColors.accentColor : Colors.transparent, 100, Colors.grey, 0.5),
                              ),
                              mWidth(12),
                              Container(
                                height: 60.0,
                                padding: EdgeInsets.all(7.0),
                                width: 60,
                                child: Image.asset("assets/images/new/payment/Mastercard.png"),
                              ),
                              mFlex(1),
                              if (selectedPaymentMethod == "MASTERCARD")
                                Container(
                                  decoration: containerRadius(CustomColors.green, 200),
                                  padding: EdgeInsets.only(top: 6, bottom: 6, left: 12, right: 12),
                                  child: Text(
                                    TranslationBase.of(context).paymentSelected,
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 11,
                                    ),
                                  ),
                                ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                if (projectViewModel!.havePrivilege(90) && !widget.isFromAdvancePayment! && widget.patientShare! >= minTamaraLimit && widget.patientShare! <= maxTamaraLimit)
                  Container(
                    width: double.infinity,
                    child: InkWell(
                      onTap: () {
                        updateSelectedPaymentMethod("TAMARA");
                      },
                      child: Card(
                        elevation: 0.0,
                        margin: EdgeInsets.fromLTRB(8.0, 16.0, 8.0, 8.0),
                        color: Colors.white,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                          side: selectedPaymentMethod == "TAMARA" ? BorderSide(color: Colors.green, width: 2.0) : BorderSide(color: Colors.transparent, width: 0.0),
                        ),
                        child: Padding(
                          padding: const EdgeInsets.all(12.0),
                          child: Row(
                            children: [
                              Container(
                                width: 24,
                                height: 24,
                                decoration: containerColorRadiusBorderWidth(selectedPaymentMethod == "TAMARA" ? CustomColors.accentColor : Colors.transparent, 100, Colors.grey, 0.5),
                              ),
                              mWidth(12),
                              Container(
                                height: 60.0,
                                padding: EdgeInsets.all(0.0),
                                width: 60,
                                child: projectViewModel!.isArabic ? Image.asset("assets/images/new/payment/tamara_ar.png") : Image.asset("assets/images/new/payment/tamara_en.png"),
                              ),
                              mFlex(1),
                              if (selectedPaymentMethod == "TAMARA")
                                Container(
                                  decoration: containerRadius(CustomColors.green, 200),
                                  padding: EdgeInsets.only(top: 6, bottom: 6, left: 12, right: 12),
                                  child: Text(
                                    TranslationBase.of(context).paymentSelected,
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 11,
                                    ),
                                  ),
                                ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                if (widget.isShowInstallments! && projectViewModel!.havePrivilege(91))
                  Container(
                    width: double.infinity,
                    child: InkWell(
                      onTap: () {
                        updateSelectedPaymentMethod("Installment");
                      },
                      child: Card(
                        elevation: 0.0,
                        margin: EdgeInsets.fromLTRB(8.0, 16.0, 8.0, 8.0),
                        color: Colors.white,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                          side: selectedPaymentMethod == "Installment" ? BorderSide(color: Colors.green, width: 2.0) : BorderSide(color: Colors.transparent, width: 0.0),
                        ),
                        child: Padding(
                          padding: const EdgeInsets.all(12.0),
                          child: Row(
                            children: [
                              Container(
                                width: 24,
                                height: 24,
                                decoration: containerColorRadiusBorderWidth(selectedPaymentMethod == "Installment" ? CustomColors.accentColor : Colors.transparent, 100, Colors.grey, 0.5),
                              ),
                              mWidth(12),
                              Container(
                                height: 60.0,
                                padding: EdgeInsets.all(7.0),
                                width: 90,
                                // child: Image.asset("assets/images/new/payment/installments.png"),
                                child: SvgPicture.asset("assets/images/new/payment/instalmt.svg"),
                              ),
                              mFlex(1),
                              if (selectedPaymentMethod == "Installment")
                                Container(
                                  decoration: containerRadius(CustomColors.green, 200),
                                  padding: EdgeInsets.only(top: 6, bottom: 6, left: 12, right: 12),
                                  child: Text(
                                    TranslationBase.of(context).paymentSelected,
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 11,
                                    ),
                                  ),
                                ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                (Platform.isIOS && projectViewModel!.havePrivilege(89))
                    ? Container(
                        width: double.infinity,
                        child: InkWell(
                          onTap: () {
                            updateSelectedPaymentMethod("ApplePay");
                          },
                          child: Card(
                            elevation: 0.0,
                            margin: EdgeInsets.fromLTRB(8.0, 16.0, 8.0, 8.0),
                            color: Colors.white,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10),
                              side: selectedPaymentMethod == "ApplePay" ? BorderSide(color: Colors.green, width: 2.0) : BorderSide(color: Colors.transparent, width: 0.0),
                            ),
                            child: Padding(
                              padding: const EdgeInsets.all(12.0),
                              child: Row(
                                children: [
                                  Container(
                                    width: 24,
                                    height: 24,
                                    decoration: containerColorRadiusBorderWidth(selectedPaymentMethod == "ApplePay" ? CustomColors.accentColor : Colors.transparent, 100, Colors.grey, 0.5),
                                  ),
                                  mWidth(12),
                                  Container(
                                    height: 60.0,
                                    padding: EdgeInsets.all(7.0),
                                    width: 60,
                                    child: SvgPicture.asset(
                                      "assets/images/new/payment/Apple_Pay.svg",
                                    ),
                                  ),
                                  mFlex(1),
                                  if (selectedPaymentMethod == "ApplePay")
                                    Container(
                                      decoration: containerRadius(CustomColors.green, 200),
                                      padding: EdgeInsets.only(top: 6, bottom: 6, left: 12, right: 12),
                                      child: Text(
                                        TranslationBase.of(context).paymentSelected,
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 11,
                                        ),
                                      ),
                                    ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      )
                    : Container(),
                SizedBox(
                  height: 150.0,
                ),
              ],
            ),
          ),
        ),
      ),
      bottomSheet: Container(
        padding: EdgeInsets.all(16),
        color: Colors.white,
        child: selectedPaymentMethod == "TAMARA"
            ? Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(TranslationBase.of(context).selectTamaraPlan, style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold)),
                        Container(
                          height: 60.0,
                          padding: EdgeInsets.all(0.0),
                          width: 60,
                          child: SvgPicture.asset("assets/images/new/payment/tamara.svg"),
                        ),
                      ],
                    ),
                  ),
                  if (tamaraInstallmentDetails != null)
                    Column(
                      children: [
                        ...List.generate(
                          tamaraInstallmentDetails!.supportedInstalments!.length,
                          (index) => Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              SizedBox(
                                height: 1,
                              ),
                              Row(
                                children: <Widget>[
                                  Expanded(
                                    flex: 1,
                                    child: InkWell(
                                      onTap: () {
                                        setState(() {
                                          selectedInstallmentPlan = tamaraInstallmentDetails!.supportedInstalments![index].instalments.toString();
                                          // getPaymentInfo(context, widget.projectID.toString(), widget.selectedProcedure.procedureID);
                                        });
                                      },
                                      child: Row(
                                        children: [
                                          Radio(
                                            value: tamaraInstallmentDetails!.supportedInstalments![index].instalments.toString(),
                                            groupValue: selectedInstallmentPlan,
                                            activeColor: Colors.red[800],
                                            toggleable: true,
                                            onChanged: (value) {
                                              setState(() {
                                                selectedInstallmentPlan = value;
                                                print(selectedInstallmentPlan);
                                              });
                                            },
                                          ),
                                          Text(
                                            tamaraInstallmentDetails!.supportedInstalments![index].instalments.toString() + " " + TranslationBase.of(context).installments,
                                            style: TextStyle(
                                              fontSize: 12.0,
                                              letterSpacing: -0.48,
                                              fontWeight: FontWeight.w600,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  )
                                ],
                              ),
                            ],
                          ),
                        ),
                        Container(
                          width: MediaQuery.of(context).size.width,
                          height: 50.0,
                          color: Colors.white,
                          child: ButtonTheme(
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10.0),
                            ),
                            minWidth: MediaQuery.of(context).size.height * 0.1,
                            height: 45.0,
                            child: CustomTextButton(
                              backgroundColor: CustomColors.green,
                              disabledForegroundColor: Color(0xFFbcc2c4).withOpacity(0.38),
                              disabledBackgroundColor: Color(0xFFbcc2c4).withOpacity(0.12),
                              elevation: 0,
                              onPressed: () {
                                widget.onSelectedMethod!(selectedPaymentMethod, selectedInstallmentPlan);
                                Navigator.pop(context, [selectedPaymentMethod, selectedInstallmentPlan]);
                              },
                              child: Text(TranslationBase.of(context).confirm.toUpperCase(), style: TextStyle(fontSize: 14.0, fontWeight: FontWeight.w600, color: Colors.white)),
                            ),
                          ),
                        ),
                      ],
                    ),
                ],
              )
            : Container(
                width: MediaQuery.of(context).size.width,
                height: 50.0,
                color: Colors.white,
                child: ButtonTheme(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  minWidth: MediaQuery.of(context).size.height * 0.1,
                  height: 45.0,
                  child: CustomTextButton(
                    backgroundColor: CustomColors.green,
                    disabledForegroundColor: Color(0xFFbcc2c4).withOpacity(0.38),
                    disabledBackgroundColor: Color(0xFFbcc2c4).withOpacity(0.12),
                    elevation: 0,
                    onPressed: () {
                      widget.onSelectedMethod!(selectedPaymentMethod, selectedInstallmentPlan);
                      Navigator.pop(context, [selectedPaymentMethod, selectedInstallmentPlan]);
                    },
                    child: Text(TranslationBase.of(context).confirm.toUpperCase(), style: TextStyle(fontSize: 14.0, fontWeight: FontWeight.w600, color: Colors.white)),
                  ),
                ),
              ),
      ),
    );
  }

  updateSelectedPaymentMethod(String selectedMethod) {
    setState(() {
      selectedPaymentMethod = selectedMethod;
    });
    // if (selectedMethod == "TAMARA") {
    //   getTamaraPaymentDetails();
    // }
  }

  getTamaraPaymentDetails() {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.getTamaraPaymentDetails(context).then((Map<dynamic, dynamic> res) {
      tamaraInstallmentDetails = TamaraInstallmentDetails.fromJson(res);
      minTamaraLimit = tamaraInstallmentDetails!.supportedInstalments![0].minLimit!.amount!;
      maxTamaraLimit = tamaraInstallmentDetails!.supportedInstalments![0].maxLimit!.amount!;
      selectedInstallmentPlan = tamaraInstallmentDetails!.supportedInstalments![0].instalments.toString();
      GifLoaderDialogUtils.hideDialog(context);
      setState(() {});
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }
}
