import { Component, OnInit } from '@angular/core';
import { InvoicesApiService } from '@fleio-api/billing/invoices/invoices-api.service';
import { IInvoiceModel } from '@fleio-api/billing/model/invoice.model';
import { ConfigService } from '@shared/config/config.service';
import { Router } from '@angular/router';
import { NotificationService } from '@shared/ui-api/notification.service';
import { formatCurrency, getCurrencySymbol } from '@angular/common';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { of } from 'rxjs';

@Component({
  selector: 'app-pay-multiple-invoices-form',
  templateUrl: './pay-multiple-invoices-form.component.html',
  styleUrls: ['./pay-multiple-invoices-form.component.scss']
})
export class PayMultipleInvoicesFormComponent extends DetailsFormBase<any> implements OnInit {
  invoices: Array<IInvoiceModel>;
  selectedInvoices = {};
  hasInvoicesToMerge = true;
  totalAmount = 0;
  upgradeInvoiceTooltip = $localize`Cannot merge service upgrade invoice.`;

  constructor(
    public invoicesApiService: InvoicesApiService,
    public config: ConfigService,
    private router: Router,
    private notificationService: NotificationService,
  ) {
    super();
  }

  ngOnInit(): void {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.merge();
    }
    this.invoices = this.object.objects;
    for (const invoice of this.invoices) {
      if (invoice.is_upgrade_invoice) {
        // service upgrade invoice cannot be merged
        continue;
      }
      this.selectedInvoices[invoice.id] = true;
      this.totalAmount += Number(invoice.balance);
    }
    const formattedCurrency = formatCurrency(
      this.totalAmount, this.config.locale, getCurrencySymbol(
        this.invoices[0].currency, 'wide', this.config.locale
      )
    );
    this.primaryAction.name = $localize`Pay ${formattedCurrency}`;
  }

  changeInvoiceSelection(invoice: IInvoiceModel) {
    this.selectedInvoices[invoice.id] = !this.selectedInvoices[invoice.id];
    if (this.selectedInvoices[invoice.id]) {
      this.totalAmount += Number(invoice.balance);
    } else {
      this.totalAmount -= Number(invoice.balance);
      if (this.totalAmount === 0) {
        this.hasInvoicesToMerge = false;
        this.primaryAction.disabled = true;
        this.primaryAction.tooltip = $localize`Select at least 1 invoice to pay.`;
      }
    }
    const formattedCurrency = formatCurrency(
      this.totalAmount, this.config.locale, getCurrencySymbol(
        this.invoices[0].currency, 'wide', this.config.locale
      )
    );
    this.primaryAction.name = $localize`Pay ${formattedCurrency}`;
    let selectedCount = 0;
    for (const id in this.selectedInvoices) {
      if (this.selectedInvoices.hasOwnProperty(id)) {
        if (this.selectedInvoices[id] === true) {
          selectedCount += 1;
          if (selectedCount > 0) {
            this.hasInvoicesToMerge = true;
            this.primaryAction.disabled = false;
            this.primaryAction.tooltip = null;
            break;
          } else {
            this.hasInvoicesToMerge = false;
            this.primaryAction.disabled = true;
            this.primaryAction.tooltip = $localize`Select at least 1 invoice to pay.`;
          }
        }
      }
    }
  }

  merge() {
    const invoicesToMerge = [];
    for (const id in this.selectedInvoices) {
      if (this.selectedInvoices.hasOwnProperty(id)) {
        if (this.selectedInvoices[id] === true) {
          invoicesToMerge.push(id);
        }
      }
    }
    if (invoicesToMerge.length === 1) {
      this.router.navigateByUrl(this.config.getPanelUrl(`billing/invoices/${invoicesToMerge[0]}`));
      return of(null);
    }
    this.objectController.loading = true;
    this.invoicesApiService.merge(
      invoicesToMerge
    ).subscribe(response => {
      this.router.navigateByUrl(this.config.getPanelUrl(`billing/invoices/${response.new_invoice_id}`));
    }, error => {
      this.objectController.loading = false;
      this.notificationService.showMessage($localize`Failed to merge invoices.`);
    });
    return of(null);
  }

}
