import { Component, OnInit } from '@angular/core';
import { ModalController, MenuController, NavController, LoadingController } from '@ionic/angular';
import { EventService } from '../../../services/event.service';
import { AddcardPage } from 'src/app/pages/card/addcard/addcard.page';
import { ActivatedRoute } from '@angular/router';
import { NgForm } from '@angular/forms';
import { EnvService } from 'src/app/services/env.service';
import { AuthService } from 'src/app/services/auth.service';
import { IchambaService } from 'src/app/services/ichamba.service';
import { TranslateService } from '@ngx-translate/core';
import { AlertService } from 'src/app/services/alert.service';

declare var OpenPay: any;

@Component({
  selector: 'app-hire',
  templateUrl: './hire.page.html',
  styleUrls: ['./hire.page.scss'],
  standalone: false
})
export class HirePage implements OnInit {

  private loading: HTMLIonLoadingElement | null = null;
  code_check = true;
  cards: any[] = [];
  code: any = null;
  device_id: any = null;
  card_id: any = null;
  supplier: any = null;
  supplier_id: any = null;
  postulation_id: any = null;
  fee: any = null;
  discount = 0;
  final_amount: any = null;
  coupon: any = null;
  cards_menu: any = null;
  paymentBypass = false;

  constructor(
    private modalController: ModalController,
    private menu: MenuController,
    private authService: AuthService,
    private alertService: AlertService,
    private ichambaService: IchambaService,
    private translateService: TranslateService,
    private activatedRoute: ActivatedRoute,
    private navCtrl: NavController,
    private loadingCtrl: LoadingController,
    private events: EventService,
    private env: EnvService,
  ) {
    this.events.subscribe('refreshcards', (data) => {
      this.card_id = null;
      this.getcards();
    });
    this.supplier = this.activatedRoute.snapshot.paramMap.get('supplier');
    this.supplier_id = this.activatedRoute.snapshot.paramMap.get('supplier_id');
    this.postulation_id = this.activatedRoute.snapshot.paramMap.get('postulation_id');
    this.fee = this.activatedRoute.snapshot.paramMap.get('fee');
    this.final_amount = this.fee;
   }

  ngOnInit() {
    this.paymentBypass = this.env.PAYMENT_BYPASS;
    if (!this.paymentBypass) {
      OpenPay.setId(this.env.MERCHANT_ID);
      OpenPay.setApiKey(this.env.PUBLIC_API_KEY);
      console.log(OpenPay.getSandboxMode());
      var deviceDataId = OpenPay.deviceData.setup("card_form");
      this.getcards();
    }
  }

  newcard() {
    this.navCtrl.navigateForward('/addcard');
  }

  getcards() {
    this.ichambaService.getCard().subscribe(
      data => {
        this.cards = data;
      }, error => {
        this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
      });
  }

  code_checker(ev: any) {
    if (ev.target.value.length > 4){
      console.log(ev.target.value.length);
      ev.target.value = ev.target.value.slice(0, 4);
    }
    this.code_check = OpenPay.card.validateCVC(ev.target.value);
    console.log(this.code_check);
  }

  selected_card(ev: any) {
    this.card_id = ev.target.value;
    console.log(this.card_id);
    if (this.card_id == "Agregar tarjeta") {
      console.log(this.card_id);
      ev.target.value = null;
      this.newcard();
    }
  }

  checkCoupon() {
    if (this.coupon) {
      this.loadingCtrl.create().then((overlay) => {
        this.loading = overlay;
        this.loading.present();
      });
      this.ichambaService.checkCoupon(this.postulation_id, this.supplier_id, this.coupon).subscribe(
        (data: any) => {
          if (data) {
            if (data['name'] == "used") {
              if (this.loading) this.loading.dismiss();
              this.alertService.presentToast(this.translateService.instant('alerts.coupon_used'));
            } else if (data['name'] == "expired") {
              if (this.loading) this.loading.dismiss();
              this.alertService.presentToast(this.translateService.instant('alerts.coupon_expired'));
            } else if (data['name'] == this.coupon) {
              if (this.loading) this.loading.dismiss();
              this.discount = (data['amount'] + (this.fee * (data['percentage']/100)));
              console.log(this.discount);
              if (this.discount > this.fee){
                this.discount = this.fee
              }
              this.final_amount = (this.fee - this.discount);
              console.log(this.final_amount);
              this.alertService.presentToast(this.translateService.instant('alerts.coupon_valid'));
            } else if (data['name'] == "success") {
              if (this.loading) this.loading.dismiss();
              this.events.publish('refreshpcontracts', 'data');
              this.navCtrl.navigateRoot('/contracts/contracted');
              this.alertService.presentToast(this.translateService.instant('alerts.hire'));
            }
          } else {
            if (this.loading) this.loading.dismiss();
            this.alertService.presentToast(this.translateService.instant('alerts.nocoupon'));
          }
        }, (error: any) => {
          if (this.loading) this.loading.dismiss();
          this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
        });
    }
  }

  createContract(form: NgForm) {
    // Si el bypass está activo, enviar con valores dummy
    if (this.paymentBypass) {
      this.loadingCtrl.create().then((overlay) => {
        this.loading = overlay;
        this.loading.present();
      });
      this.ichambaService.createContract(this.postulation_id, this.supplier_id, 'BYPASS', this.coupon, '000', 'BYPASS').subscribe(
        (data: any) => {
          if (data['type'] == "error") {
            if (this.loading) this.loading.dismiss();
            this.alertService.presentToast(data['message']);
          } else if (data['name'] == "used") {
            if (this.loading) this.loading.dismiss();
            this.alertService.presentToast(this.translateService.instant('contracts.coupon_used'));
          } else if (data['name'] == "expired") {
            if (this.loading) this.loading.dismiss();
            this.alertService.presentToast(this.translateService.instant('contracts.coupon_expired'));
          } else {
            if (this.loading) this.loading.dismiss();
            this.events.publish('refreshpcontracts', 'data');
            this.navCtrl.navigateRoot('/contracts/contracted');
            this.alertService.presentToast(this.translateService.instant('alerts.hire'));
          }
        }, (error: any) => {
          if (this.loading) this.loading.dismiss();
          this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
        });
      return;
    }

    if (this.card_id != "Agregar tarjeta") {
      if (this.code_check) {
            let code = form.value.code;
            let device_id = (<HTMLInputElement>document.getElementById('deviceDataId')).value;
            console.log(device_id);

            this.loadingCtrl.create().then((overlay) => {
              this.loading = overlay;
              this.loading.present();
            });
            this.ichambaService.createContract(this.postulation_id, this.supplier_id, this.card_id, this.coupon, code, device_id).subscribe(
              (data: any) => {
                if (data['type'] == "error") {
                  if (this.loading) this.loading.dismiss();
                  this.alertService.presentToast(data['message']);
                } else if (data['name'] == "used") {
                  if (this.loading) this.loading.dismiss();
                  this.alertService.presentToast(this.translateService.instant('contracts.coupon_used'));
                } else if (data['name'] == "expired") {
                  if (this.loading) this.loading.dismiss();
                  this.alertService.presentToast(this.translateService.instant('contracts.coupon_expired'));
                } else {
                  if (this.loading) this.loading.dismiss();
                  this.events.publish('refreshpcontracts', 'data');
                  this.navCtrl.navigateRoot('/contracts/contracted');
                  this.alertService.presentToast(this.translateService.instant('alerts.hire'));
                }
              }, (error: any) => {
                if (this.loading) this.loading.dismiss();
                this.alertService.presentToast(this.translateService.instant('alerts.error') + error['status']);
              });
            //console.log(onSuccess.data.id);
            //console.log(document.getElementById('deviceDataId').value);
      }
    } else {
      this.alertService.presentToast(this.translateService.instant('alerts.select_card'));
    }
  }

}
