import { Component, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IInvoiceModel } from '@fleio-api/billing/model/invoice.model';
import { IInvoicePaymentOptionsModel } from '@fleio-api/billing/model/invoice-payment-options.model';
import { InvoicesApiService } from '@fleio-api/billing/invoices/invoices-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { RefreshService } from '@shared/ui-api/refresh.service';
import { ConfigService } from '@shared/config/config.service';
import { IGatewayModel } from '@fleio-api/billing/model/gateway.model';

@Component({
  selector: 'app-invoice-add-payment',
  templateUrl: './invoice-add-payment.component.html',
  styleUrls: ['./invoice-add-payment.component.scss']
})
export class InvoiceAddPaymentComponent extends DetailsComponentBase<IInvoiceModel> implements OnInit {
  paymentOptions: IInvoicePaymentOptionsModel;
  showPaymentOptions: boolean;
  creditBalance: {
    currency: string;
    amount: number;
  };
  selectedGateway: any;
  saveCard: boolean;

  constructor(
    public config: ConfigService,
    private invoiceApi: InvoicesApiService,
    private notificationService: NotificationService,
    private refreshService: RefreshService,
  ) {
    super();
  }

  gatewayTrackBy(index, gateway: IGatewayModel) {
    return gateway.name;
  }

  savedCardsTrackBy(index, card) {
    return card.pay_method_id;
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.dataChanged$.subscribe(objectController => {
        this.showPaymentOptions = false;
        const obj = objectController.object as IInvoiceModel;
        if (obj && obj.id) {
          this.paymentOptions = obj.payment_options;
          if (this.paymentOptions?.creditBalance) {
            this.creditBalance = this.paymentOptions.creditBalance.find(
              b => b.currency === this.object.currency
            );
          } else {
            this.creditBalance = null;
          }

          if (this.paymentOptions?.gateways) {
            this.showPaymentOptions = this.paymentOptions.gateways.length > 0;
          }
          if (this.creditBalance) {
            this.showPaymentOptions = true;
          }
        }
      });
    }
  }

  payNow() {
    if (this.selectedGateway === 'credit') {
      this.invoiceApi.payFromCredit(this.object.id).subscribe((response) => {
        this.notificationService.showMessage(response.detail);
        this.refreshService.refresh();
      });
    } else if (this.selectedGateway.pay_method_id) {
      // this is a saved card, use it to pay without entering card data again
      const savedCard = this.selectedGateway;
      this.authSvc.generateOtpToken().subscribe(token => {
        let params = `fleio-token=${token}&invoice=${encodeURIComponent(this.object.id)}`;
        params += `&pay_method_id=${encodeURIComponent(savedCard.pay_method_id)}`;
        window.location.href = this.config.getPanelApiUrl(
          'billing/gateway/' + savedCard.gateway_name + '/pay_invoice?' + params,
        );
      });
    } else {
      const gatewayDetails = this.selectedGateway as IGatewayModel;
      if (gatewayDetails?.name) {
        this.authSvc.generateOtpToken().subscribe(token => {
          let params = `fleio-token=${token}&invoice=${encodeURIComponent(this.object.id)}`;
          if (this.saveCard) {
            params = params + '&recurring=True';
          }
          window.location.href = this.config.getPanelApiUrl(
            'billing/gateway/' + gatewayDetails.name + '/pay_invoice?' + params,
          );
        });
      }
    }
  }
}
