import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IPricingPlanModel } from '@fleio-api/openstack/model/pricing-plan.model';
import { PricingPlansApiService } from '@fleio-api/openstack/pricing-plan/pricing-plans-api.service';
import { UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
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-pricing-plan-delete',
  templateUrl: './pricing-plan-delete.component.html',
  styleUrls: ['./pricing-plan-delete.component.scss']
})
export class PricingPlanDeleteComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  alternativePlans: IPricingPlanModel[] = null;
  deleteOptions: UntypedFormGroup = new UntypedFormGroup({
    selectedPlan: new UntypedFormControl('', Validators.required),
  });
  selectedPlan = this.deleteOptions.controls.selectedPlan;
  dialogTitle = $localize`Delete plan ${this.data?.planToDelete?.name}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Delete`,
      primary: true,
      callback: () => this.delete(),
    }),
  ];
  dialogForm = this.deleteOptions;
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<PricingPlanDeleteComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      planToDelete: IPricingPlanModel;
      isStaff: boolean;
    },
    private pricingPlansApiService: PricingPlansApiService,
  ) {
  }

  ngOnInit() {
    if (this.data && this.data.planToDelete) {
      this.loading = true;
      this.pricingPlansApiService.getAlternativePlans(
        this.data.planToDelete, this.data.isStaff
      ).subscribe(alternativePlans => {
        this.alternativePlans = alternativePlans;
        if (!this.alternativePlans.length && this.data.planToDelete.services_count) {
          this.dialogActions[0].disabled = true;
        }
        if (!this.data.planToDelete.services_count) {
          this.deleteOptions.controls.selectedPlan.clearValidators();
          this.deleteOptions.controls.selectedPlan.reset();
        }
        this.loading = false;
      });
    }
  }

  delete() {
    this.loading = true;
    let queryParams = {} as Record<string, any>;
    if (this.selectedPlan.value) {
      queryParams.plan_to_migrate = this.selectedPlan.value;
    }
    this.pricingPlansApiService.delete(
      this.data.planToDelete.id,
      queryParams,
    ).subscribe({
      next: result => {
        if (result) {
          this.dialogRef.close($localize`Plan deleted successfully`);
        } else {
          this.dialogRef.close($localize`Failed to delete plan`);
        }
      }, error: error => {
        if (error?.error?.detail) {
          this.formErrors.setBackendErrors(error.error.detail);
        }
      }
    }).add(() => {
      this.loading = false;
    });
  }
}
