import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';

@Component({
  selector: 'app-change-credit-dialog',
  templateUrl: './change-credit-dialog.component.html',
  styleUrls: ['./change-credit-dialog.component.scss']
})
export class ChangeCreditDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  changeCreditForm = this.formBuilder.group({
    change_type: ['add', Validators.required],
    amount: [null, [Validators.required, ValidatorsHelper.requiredNumericValueValidator, Validators.min(0.01)]],
  });
  dialogTitle = $localize`Edit credit for ${this.data?.client?.name}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Add credit`,
      primary: true,
      callback: () => this.changeCredit(),
    }),
  ];
  dialogForm = this.changeCreditForm;
  loading = false;
  backendErrors = {};

  constructor(
    public dialogRef: MatDialogRef<ChangeCreditDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      client: IClientModel;
      credit: {
        client: FleioId;
        amount: number;
        currency: string;
      };
    },
    private formBuilder: UntypedFormBuilder,
    private clientsApiService: ClientsApiService,
  ) { }

  ngOnInit(): void {
    this.changeCreditForm.controls.change_type.valueChanges.subscribe(value => {
      if (value === 'add') {
        this.dialogActions[0].name = $localize`Add credit`;
      } else {
        this.dialogActions[0].name = $localize`Subtract credit`;
      }
    });
  }

  public changeCredit() {
    if (!this.changeCreditForm.valid) {
      return;
    }
    this.loading = true;
    this.clientsApiService.changeCredit(
        this.data.client.id,
        this.changeCreditForm.controls.change_type.value === 'add',
        this.changeCreditForm.controls.amount.value,
        this.data.credit.currency,
        this.data.credit.currency,
      ).subscribe(result => {
      this.dialogRef.close(true);
    }, error => {
      this.backendErrors = error.error;
      this.formErrors.setBackendErrors(error.error);
    }).add(() => {
      this.loading = false;
    });
  }
}
