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 { IConfigOptionModel } from '@fleio-api/billing/model/config-option.model';
import { ConfigurableOptionsChoiceApiService } from '@fleio-api/billing/configurable-options/configurable-option-choice-api.service';
import { IConfigurableOptionChoiceModel } from '@fleio-api/billing/model/configurable-option-choice.model';
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';

@Component({
  selector: 'app-edit-option-choice-dialog',
  templateUrl: './edit-option-choice-dialog.component.html',
  styleUrls: ['./edit-option-choice-dialog.component.scss']
})
export class EditOptionChoiceDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  backendErrors: Record<string, unknown> = {};
  editChoiceForm: UntypedFormGroup = this.formBuilder.group({
    label: ['', Validators.required],
    choice: ['', Validators.required],
    position: [null, Validators.min(0)],
  });
  dialogTitle: string;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Save choice`,
      primary: true,
      callback: () => this.addChoice(),
    }),
  ];
  dialogForm = this.editChoiceForm;
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<EditOptionChoiceDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      option?: IConfigOptionModel;
      choice?: IConfigurableOptionChoiceModel;
    },
    private formBuilder: UntypedFormBuilder,
    private configurableOptionsChoiceApiService: ConfigurableOptionsChoiceApiService,
  ) {
  }

  ngOnInit() {
    if (this.data.choice) {
      this.dialogTitle = $localize`Edit choice`;
      this.editChoiceForm.patchValue(this.data.choice);
    } else {
      this.dialogTitle = $localize`Add choice`;
    }
  }

  addChoice() {
    const value = this.editChoiceForm.value as IConfigurableOptionChoiceModel;

    if (this.data.option) {
      value.option = this.data.option.id;
    }

    let request;

    if (this.data.choice && this.data.choice.id) {
      value.id = this.data.choice.id;
      request = this.configurableOptionsChoiceApiService.update(value.id, value);
    } else {
      request = this.configurableOptionsChoiceApiService.create(value);
    }

    this.loading = true;
    request.subscribe(() => {
        this.dialogRef.close(true);
      },
      (error) => {
        if (error.error) {
          this.backendErrors = error.error;
          this.formErrors.setBackendErrors(error.error);
        }
      }
    ).add(() => {
      this.loading = false;
    });
  }
}
