import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { IProductModel } from '@fleio-api/billing/model/product.model';
import { IProductCycleModel } from '@fleio-api/billing/model/product-cycle.model';
import { ProjectsApiService } from '@fleio-api/openstack/project/projects-api.service';
import { AuthService } from '@shared/auth/auth.service';
import {
  OpenstackBillingServicesApiService
} from '@fleio-api/openstack/billing/services/openstack-billing-services-api.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';

@Component({
  selector: 'app-create-openstack-service-dialog',
  templateUrl: './create-openstack-service-dialog.component.html',
  styleUrls: ['./create-openstack-service-dialog.component.scss']
})
export class CreateOpenstackServiceDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  backendErrors: Record<string, unknown> = {};
  createOpenstackServiceForm = this.formBuilder.group({
    product_id: ['', Validators.required],
    product_cycle_id: [null, Validators.required],
    create_new_project: [false],
    project_id: [null, Validators.required]
  });
  dialogTitle = $localize`Create OpenStack service`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Create OpenStack service`,
      primary: true,
      callback: () => this.createOpenstackService(),
    }),
  ];
  dialogForm = this.createOpenstackServiceForm;
  loading = false;

  availableProducts: IProductModel[];
  selectedProductCycles: IProductCycleModel[];
  project = this.createOpenstackServiceForm.controls.project_id;
  projectSelectedPlaceholder = $localize`Project`;
  projectUnselectedPlaceholder = $localize`Select project ...`;

  constructor(
    public dialogRef: MatDialogRef<CreateOpenstackServiceDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      client: IClientModel;
      availableProducts;
    },
    private formBuilder: UntypedFormBuilder,
    private openstackBillingServicesApiService: OpenstackBillingServicesApiService,
    public projectsApi: ProjectsApiService,
    public auth: AuthService,
  ) {
  }

  ngOnInit() {
    this.createOpenstackServiceForm.controls.product_id.valueChanges.subscribe(
      productId => {
        this.selectedProductCycles = [];
        for (const product of this.availableProducts) {
          if (product.id === productId) {
            this.selectedProductCycles = product.cycles;
          }
        }
        this.createOpenstackServiceForm.controls.product_cycle_id.setValue(null);
      }
    );

    if (this.data && this.data.client && this.data.availableProducts) {
      this.availableProducts = this.data.availableProducts;
      if (this.availableProducts.length > 0) {
        this.createOpenstackServiceForm.patchValue({
          product_id: this.availableProducts[0].id,
          product_cycle_id: this.availableProducts[0].cycles[0].id,
        });
      }
    }

    this.createOpenstackServiceForm.controls.create_new_project.valueChanges.subscribe(
      createNewProject => {
        if (createNewProject) {
          this.createOpenstackServiceForm.controls.project_id.disable();
        } else {
          this.createOpenstackServiceForm.controls.project_id.enable();
        }
      }
    );

    if (this.data && this.data.client) {
      if (!this.auth.feature('ui.openstack.service.select-project')) {
        this.createOpenstackServiceForm.controls.create_new_project.setValue(true);
      }
    }
  }

  createOpenstackService() {
    if (this.createOpenstackServiceForm.invalid) {
      return;
    }
    const params = this.createOpenstackServiceForm.value;
    params.client_id = this.data.client.id;
    if (params.project_id) {
      params.project_id = params.project_id.project_id;
    }

    this.loading = true;
    this.openstackBillingServicesApiService.createOpenstackService(params).subscribe({
      next: () => {
        this.dialogRef.close(true);
      },
      error: (error) => {
        if (error.error) {
          this.backendErrors = error.error;
          this.formErrors.setBackendErrors(error.error);
        }
      }
    }).add(() => {
      this.loading = false;
    });
  }
}
