import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { CurrenciesApiService } from '@fleio-api/core/currencies-api.service';
import { ICurrencyModel } from '@fleio-api/billing/model/currency.model';
import { ICurrencyCreateOptions } from '@fleio-api/billing/model/currency-create-options';
import { EMPTY, Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { IIcon } from '@shared/ui/common/interfaces/icon';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';

@Component({
  selector: 'app-edit-currency-dialog',
  templateUrl: './edit-currency-dialog.component.html',
  styleUrls: ['./edit-currency-dialog.component.scss']
})
export class EditCurrencyDialogComponent implements IBaseDialog, OnInit {
  currencyForm: UntypedFormGroup = this.formBuilder.group({
    code: ['', Validators.required],
    rate: [1, [Validators.required, ValidatorsHelper.requiredNumericValueValidator]],
    is_default: [false],
  });
  dialogTitle = null;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Save currency`,
      primary: true,
      callback: () => this.save(),
    }),
  ];
  dialogForm = this.currencyForm;
  loading = false;
  currency: ICurrencyModel;
  creating: boolean;
  createOptions: ICurrencyCreateOptions;
  @ViewChild('formErrors') formErrors;
  backendErrors: Record<string, unknown> = {};
  codeSwitchMapFn: (search: string) => Observable<any>;
  codePlaceholderSelected = $localize`Code`;
  codePlaceholderUnselected = $localize`Select code ...`;

  defaultCurrencyInfo = {
    name: 'info',
    verticalAlign: 'middle',
    fontSize: '20px',
    marginLeft: '5px',
    marginTop: '2px',
    tooltip: $localize`The default currency is set on new client sign-up\nand is used for limits defined in Configurations.`,
  } as IIcon;

  constructor(
    public dialogRef: MatDialogRef<EditCurrencyDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      currency: ICurrencyModel;
      defaultCurrency: ICurrencyModel;
      createOptions: ICurrencyCreateOptions;
    },
    private formBuilder: UntypedFormBuilder,
    private currencyApi: CurrenciesApiService,
    private notificationService: NotificationService,
  ) {
  }

  ngOnInit() {
    if (this.data) {
      this.createOptions = this.data.createOptions;
      if (this.data.currency) {
        this.currency = this.data.currency;
        if (this.currency.is_default) {
          this.currencyForm.controls.is_default.disable();
          this.dialogActions[0].disabled = true;
        }
        this.currencyForm.controls.code.disable();
        this.creating = false;
        this.dialogTitle = $localize`Edit currency ${this.currency.code}`;
        this.currencyForm.patchValue(this.currency);
      } else {
        this.currency = {code: null, rate: null};
        this.creating = true;
        this.dialogTitle = $localize`Create currency`;
      }

      this.codeSwitchMapFn = (search) => {
        const lowerCaseValue = search.toLocaleLowerCase();
        return of(this.createOptions.codes.filter(
          code => code.toLocaleLowerCase().includes(lowerCaseValue)
        ));
      };
    }
  }

  protected displayControlErrors() {
    Object.keys(this.currencyForm.controls).map(name => {
      const control = this.currencyForm.controls[name];
      if (control.invalid) {
        control.markAsTouched();
      }
    });
  }

  protected setErrors(backendErrors: Record<string, any>) {
    this.backendErrors = backendErrors;
    this.formErrors.setBackendErrors(backendErrors);
  }

  save() {
    if (this.currencyForm.invalid) {
      this.displayControlErrors();
      return;
    }

    this.currency = this.currencyForm.getRawValue();

    let request;
    if (this.creating) {
      request = this.currencyApi.create(this.currency);
    } else {
      request = this.currencyApi.update(this.currency.code, this.currency);
    }

    this.loading = true;
    request.pipe(catchError((error) => {
      if (error.error) {
        this.setErrors(error.error);
        return EMPTY;
      } else {
        throw error;
      }
    })).subscribe(() => {
      this.notificationService.showMessage(
        this.creating ? $localize`Currency created` : $localize`Currency saved`
      );
      this.dialogRef.close(true);
    }).add(() => {
      this.loading = false;
    });
  }
}
