import { Component, OnInit } from '@angular/core';
import { IInvoiceModel } from '@fleio-api/billing/model/invoice.model';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { IInvoicePaymentOptionsModel } from '@fleio-api/billing/model/invoice-payment-options.model';
import { EMPTY } from 'rxjs';
import { catchError } from 'rxjs/operators';
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 { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';

@Component({
  selector: 'app-invoice-details-add-payment',
  templateUrl: './invoice-details-add-payment.component.html',
  styleUrls: ['./invoice-details-add-payment.component.scss']
})
export class InvoiceDetailsAddPaymentComponent extends DetailsFormBase<IInvoiceModel> implements OnInit {
  addPaymentForm = this.formBuilder.group({
    external_id: [''],
    extra_info: [''],
    date_initiated: [Validators.required],
    gateway: ['', Validators.required],
    currency: [{value: '', disabled: true}, Validators.required],
    amount: [0, [ValidatorsHelper.requiredNumericValueValidator, ValidatorsHelper.nonZeroValidator, Validators.min(0)]],
    fee: [0, ValidatorsHelper.requiredNumericValueValidator],
  });

  public paymentOptions: IInvoicePaymentOptionsModel;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private activatedRoute: ActivatedRoute,
    private invoicesApi: InvoicesApiService,
    private notification: NotificationService,
    private refreshService: RefreshService,
    public config: ConfigService,
  ) {
    super();
  }

  protected initTabData() {
    super.initTabData();
    if (this.object) {
      this.paymentOptions = this.activatedRoute.snapshot.data.paymentOptions;
      if (this.object && this.paymentOptions && this.paymentOptions.gateways.length) {
        this.addPaymentForm.patchValue({
          date_initiated: new Date(),
          amount: this.object.balance,
          currency: this.object.currency,
          gateway: this.paymentOptions.gateways[0].id,
        });
      }
    }
  }

  ngOnInit() {
    super.ngOnInit();
  }

  public addPayment() {
    this.validate();
    if (this.addPaymentForm.invalid) {
      Object.keys(this.formGroup.controls).map(name => {
        const control = this.formGroup.controls[name];
        if (control.invalid) {
          control.markAsTouched();
        }
      });
    } else {
      this.objectController.loading = true;
      const value = this.addPaymentForm.value;
      value.invoice = this.object.id;
      const request = this.invoicesApi.addPayment(this.object.id, value);

      request.pipe(catchError((error) => {
        this.objectController.loading = false;
        if (error.error) {
          this.setErrors(error.error);
          return EMPTY;
        } else {
          throw error;
        }
      })).subscribe(() => {
        this.notification.showMessage($localize`Payment added`);
        this.switchTab(0); // go back on first page of invoice
        this.refreshService.refresh(() => {
          this.objectController.loading = false; // workaround in order to hide loader only after tab switch
        });
      });
    }
  }
}
