import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { InvoicesApiService } from '@fleio-api/billing/invoices/invoices-api.service';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';

@Component({
  selector: 'app-add-credit-form',
  templateUrl: './add-credit-form.component.html',
  styleUrls: ['./add-credit-form.component.scss']
})
export class AddCreditFormComponent extends DetailsFormBase<IClientModel> implements OnInit {
  addCreditForm = this.formBuilder.group({
    credit: ['', [ValidatorsHelper.requiredNumericValueValidator, Validators.min(0)]],
  });
  amountPlaceholder: string;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private invoicesApiService: InvoicesApiService,
    private router: Router,
    private config: ConfigService,
  ) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.addCredit();
    }
    if (this.object && this.object.id) {
      this.amountPlaceholder = $localize`Amount in ${this.object.currency}`;
    }
  }

  private addCredit(): Observable<IActionResult> {
    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return;
    }

    const value = this.addCreditForm.value as any;
    this.objectController.loading = true;
    this.invoicesApiService.addCredit(value.credit).subscribe((response) => {
      const invoiceId = response.id;
      this.router.navigateByUrl(
        this.config.getPanelUrl('billing/invoices', invoiceId)
      ).catch(() => {
      });
    }, error => {
      this.objectController.loading = false;
      if (error.error) {
        this.setErrors(error.error);
      }
    });
    return of(null);
  }
}
