import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IProductModel } from '@fleio-api/billing/model/product.model';
import { ProductsApiService } from '@fleio-api/billing/products/product-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-associate-option-dialog',
  templateUrl: './product-associate-option-dialog.component.html',
  styleUrls: ['./product-associate-option-dialog.component.scss']
})
export class ProductAssociateOptionDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  associateOptionForm = this.formBuilder.group({
    selectedOption: [null, Validators.required]
  });
  dialogTitle = $localize`Associate option`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Associate option`,
      primary: true,
      callback: () => this.associateOption(),
    }),
  ];
  dialogForm = this.associateOptionForm;
  loading = false;

  selectedOptionCtrl = this.associateOptionForm.controls.selectedOption;
  selectedOption;
  availableOptions: Array<Record<string, any>>;
  servicesCount;

  constructor(
    public dialogRef: MatDialogRef<ProductAssociateOptionDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { product: IProductModel },
    private formBuilder: UntypedFormBuilder,
    private productsApiService: ProductsApiService,
    private notificationService: NotificationService,
  ) {
  }

  ngOnInit() {
    if (this.data && this.data.product) {
      this.loading = true;
      this.productsApiService.getConfigurableOptions(this.data.product.id).subscribe({
        next: response => {
          this.loading = false;
          this.availableOptions = response.available_options;
          this.servicesCount = response.services_count;
        }, error: () => {
          this.dialogRef.close(false);
          this.loading = false;
          this.notificationService.showMessage($localize`Failed to get configurable options for product.`);
        }
      });
    }
    this.selectedOptionCtrl.valueChanges.subscribe(value => {
      this.selectedOption = this.availableOptions.find(option => option.id === value);
    });
  }

  associateOption() {
    this.loading = true;
    this.productsApiService.associateOption(
      this.data.product.id,
      this.selectedOptionCtrl.value
    ).subscribe({
      next: () => {
        this.dialogRef.close(true);
      }, error: error => {
        this.formErrors.setBackendErrors(error.error, this.formErrors.formGroup);
      }
    }).add(() => {
      this.loading = false;
    });
  }
}
