import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { IProductGroupModel } from '@fleio-api/billing/model/product-group.model';
import { ProductGroupsApiService } from '@fleio-api/billing/product-groups/product-groups-api.service';
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';

@Component({
  selector: 'app-product-group-edit-form',
  templateUrl: './product-group-edit-form.component.html',
  styleUrls: ['./product-group-edit-form.component.scss']
})
export class ProductGroupEditFormComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  productGroupForm = this.formBuilder.group({
    name: ['', Validators.required],
    description: [''],
  });
  dialogTitle = null;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Save product group`,
      primary: true,
      callback: () => this.saveProductGroup(),
    }),
  ];
  dialogForm = this.productGroupForm;
  backendErrors: Record<string, unknown> = {};
  loading = false;
  addForm: boolean;
  fieldRequiredTxt = $localize`This field is required!`;

  constructor(
    public dialogRef: MatDialogRef<ProductGroupEditFormComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      productGroup: IProductGroupModel;
    },
    private formBuilder: UntypedFormBuilder,
    private productGroupsApiService: ProductGroupsApiService,
  ) {
  }

  saveProductGroup() {
    if (!this.productGroupForm.valid) {
      return;
    }
    const value = this.productGroupForm.value;
    this.loading = true;
    if (this.addForm) {
      this.productGroupsApiService.create(
        value
      ).subscribe({
        next: () => {
          this.loading = false;
          this.dialogRef.close(true);
        }, error: error => {
          this.loading = false;
          this.backendErrors = error.error;
          this.formErrors.setBackendErrors(error.error);
        }
      });
    } else {
      this.productGroupsApiService.update(this.data.productGroup.id, value).subscribe({
        next: () => {
          this.loading = false;
          this.dialogRef.close(true);
        }, error: error => {
          this.loading = false;
          this.backendErrors = error.error;
          this.formErrors.setBackendErrors(error.error);
        }
      });
    }
  }

  ngOnInit(): void {
    this.addForm = !this.data.productGroup;
    if (!this.addForm) {
      this.dialogTitle = $localize`Edit product group`;
      this.productGroupForm.patchValue(this.data.productGroup);
    } else {
      this.dialogTitle = $localize`Create product group`;
    }
  }
}
