import { Component, OnInit } from '@angular/core';
import {AlertController, LoadingController, NavController} from "@ionic/angular";
import {Router} from "@angular/router";
import {SessionDataProviderService} from "../../store/session-data-provider.service";
import {WrenchService} from "../../services/wrench.service";
import {BlogDataService} from "../../store/blog-data.service";
import {UserWalletService} from "../../store/user-wallet.service";
import {Unary} from "@angular/compiler";
//import {Flutterwave, AsyncPaymentOptions} from "flutterwave-angular-v3"

@Component({
  selector: 'app-addcredit',
  templateUrl: './addcredit.page.html',
  styleUrls: ['./addcredit.page.scss'],
})
export class AddcreditPage implements OnInit {
    walletData:any;
    tabs = 'bank_redeem';
    curr_balance:number =0;
    currency_description : string='';
    currency_code:string='';
    wallet_uid:string='';
    isDisabled:boolean=true;
    isProcessDisabled:boolean=false;
    curr_page:string= 'redeem_start';
    processor:number=0;
    isModalOpen:boolean = false;
    isModalOpenBackdrop:boolean = false;
    card_level:number=200;



    publicKey = "FLWPUBK_TEST-XXXXXXXXX";

    customerDetails = { name: 'Demo Customer  Name', email: 'customer@mail.com', phone_number: '08100000000'}

    customizations = {title: 'Customization Title', description: 'Customization Description', logo: 'https://flutterwave.com/images/logo-colored.svg'}

    meta = {'counsumer_id': '7898', 'consumer_mac': 'kjs9s8ss7dd'}
/*
    paymentData : AsyncPaymentOptions = {
        public_key: this.publicKey,
        tx_ref: this.generateReference(),
        amount: 10,
        currency: 'NGN',
        payment_options: 'card,ussd',
        meta: this.meta,
        customer: this.customerDetails,
        customizations: this.customizations,
    }
*/

  constructor(private navctr: NavController,
              private router: Router,
              public sessionDataProviderService: SessionDataProviderService,
              private wrenchService: WrenchService,
              public blogDataService: BlogDataService,
              private loadingCtrl: LoadingController,
              public alertController: AlertController,
           /*   private flutterwave: Flutterwave,*/
              public userWalletService: UserWalletService) {
      this.walletData  =  this.router.getCurrentNavigation().extras.state;
      if ( this.walletData != undefined ){
          this.curr_balance = this.walletData.amount*0.01;
          this.currency_code = this.walletData.code;
          this.currency_description = this.walletData.description;
          this.wallet_uid= this.walletData.wallet_uid;
          this.processor = this.walletData.processor;
      }
      else{
          this.onBack();
      }

  }

  ngOnInit() {
      this.getUsersCardsList();
  }
  onBack() {
      this.setCloseModal();
   // this.navctr.back();

  }

    setCcType(cc_type){
      this.card_level = cc_type;
    }
  usrData: {
    action:number, member_id: number, uid: string, sessionid: string, limit:20, page:1,offset: 0
  };

  usersCardsTotalData:any;
  usersCardsData: any;
  getUsersCardsList(){
    this.usrData =
        {
          action:11055,
          member_id: this.sessionDataProviderService.member_id,
          uid: this.sessionDataProviderService.member_uid,
          sessionid: this.sessionDataProviderService.session ,
          limit:20, page:1,offset: 0
        };

    this.wrenchService.getusersCardList(this.usrData).subscribe(
        usersCardsTotalData => {
          this.usersCardsTotalData = usersCardsTotalData;
          console.log("usersCardsTotalData TOTAL  RETURN->", this.usersCardsTotalData);
          this.usersCardsData = this.usersCardsTotalData.result_list;
          // debugger;
          console.log("usersCardsData RETURN DATA->", this.usersCardsData);
          //this.total_family = this.familyData.length;
        }
    );

  }

    payViaPromise() {
        // this.flutterwave.asyncInlinePay(this.paymentData).then(
        //     (response) =>{
        //         console.log("Promise Res" , response)
        //         this.flutterwave.closePaymentModal(5)
        //     }
        // )
    }
    generateReference(): string {
        let date = new Date();
        return date.getTime().toString();
    }


  startCreditData:{
    member_id:number,
    sessionid:string,
    uid:string,
    currency: string,
    amount:number,
    card_uid: string,
    action:number
};

    startCreditResult:any;
    async   contineAddCredit(processor){
        const loading = await this.loadingCtrl.create({
            message: 'Starting...',
            duration: 2500,
        });
        this.startCreditData = {
            member_id:this.sessionDataProviderService.member_id,
            sessionid:this.sessionDataProviderService.session,
            uid:this.sessionDataProviderService.member_uid,
            currency: this.currency_code,
            amount:this.amount*100,
            card_uid: this.payment_card,
            action:11053
        };
        this.isDisabled=true;
        loading.present();
        this.wrenchService.startCredit(this.startCreditData).subscribe(
            startCreditResult => {
                loading.dismiss();
                console.log("startCreditResult TOTAL  RETURN->", this.startCreditResult);
                if ( startCreditResult!=undefined && startCreditResult.credit_reference!='' ){
                    this.startCreditResult = startCreditResult;


                    this.isModalOpen = true;
                    this.isModalOpenBackdrop= true;
                }
            }
        );
    }
    setCloseModal(){
        this.isModalOpen = false;
        setTimeout(()=>{
            this.isModalOpenBackdrop= false;
            this.myWallet();
            },1000);
    }

    amount:number =0;
    fee:number = 0;
    fee_display: string;
    total:number = 0;
    total_display: string;
    recipient:string ='';
    recipient_name:string ='';
    payment_card:string = '';
    selPaymentCard:any;

    feeReturn: any;
    refreshFee(){
        this.isDisabled = true;
        this.total =  this.fee = 0;
        console.log("Refresh Fee******************");
        // this.usrData = {action:33025,
        //     member_id: this.sessionDataProviderService.member_id,
        //     uid: this.sessionDataProviderService.member_uid,
        //     sessionid: this.sessionDataProviderService.session ,
        //     limit:20, page:1,offset: 0, amount: this.amount*100}
        // if (this.amount <= 0 ) return;


        // this.wrenchService.sendMoneyFee(this.usrData).subscribe(
        //     feeReturn => {
        //         this.feeReturn = feeReturn;
        //         if ( this.feeReturn != null && this.feeReturn.processing_fee >= 0 ){
                    this.fee = 0; // this.feeReturn.processing_fee*0.01;
                    var num = new Number(this.fee);
                    this.fee_display = num.toFixed(2);
                    // parseFloat("123.456").toFixed(2);
                    this.total = this.fee+this.amount; // this.feeReturn.total_amount*0.01;
                    var numt = new Number(this.total);
                    this.total_display= numt.toFixed(2);
                    if (this.total > 100 && this.processor==3030 ){
                        this.isDisabled=false;
                    }
                    if (this.total > 5 && this.processor==5000 && this.payment_card !="" ){
                       this.selPaymentCard = this.usersCardsData.filter((item) => item.card_uid == this.payment_card)[0];
                        this.isDisabled=false;
                    }
        //         }
        //     }
        // );


        //  this.total =  this.fee + this.amount;
    }

    credit_confirmation :string='';

    creditResult:any;
   async processPayment(processor){
       this.credit_confirmation='';
        const loading = await this.loadingCtrl.create({
            message: 'Processing...',
            duration: 3500,
        });

        if(this.processor == 3030){
            debugger;
            this.payViaPromise();
        }
        if (this.processor == 5000){
            this.isProcessDisabled = true;
            this.payPevCreditData={
                member_id:this.sessionDataProviderService.member_id,
                sessionid:this.sessionDataProviderService.session,
                uid:this.sessionDataProviderService.member_uid,
                currency: this.currency_code,
                amount:this.startCreditResult.amount,
                credit_reference:this.startCreditResult.credit_reference,
                card_uid: this.startCreditResult.card_uid,
                action:11056
            };


            loading.present();
            this.wrenchService.payPrevCard(this.payPevCreditData).subscribe(
                creditResult => {
                    loading.dismiss();
                    console.log("creditResult TOTAL  RETURN->", this.creditResult);
                    if ( creditResult!=undefined && creditResult.internal_return > 0 && creditResult.confirmation !=''){
                        this.userWalletService.getWalletData(); // refresh the wallet
                        this.credit_confirmation = creditResult.confirmation;
                        this.showCrediAlert("Credit Processing","Completed");
                    }
                }
            );

        }


    }

    myWallet(){
        this.router.navigate(['tabs/tab4']);
    }

    payPevCreditData:{
        member_id:number,
        sessionid:string,
        uid:string,
        currency: string,
        amount:number,
        credit_reference:string,
        card_uid: string,
        action:number
    };

    async showCrediAlert(mtitle: string, amessage: string) {

        const alert = await this.alertController.create({
            header: 'WrenchBoard',
            subHeader: mtitle,
            message: amessage,
            buttons: [{
                text: 'OK',
                role: 'confirm',
                handler: () => {
                    this.onBack();
                },
            }],
        });
        await alert.present();
    }
}
