import { Component, Inject, OnInit } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IServiceModel } from '@fleio-api/billing/model/service.model';
import { ServicesApiService } from '@fleio-api/billing/services/service-api.service';
import { NotificationService } from '@shared/ui-api/notification.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-service-request-cancellation',
  templateUrl: './service-request-cancellation.component.html',
  styleUrls: ['./service-request-cancellation.component.scss']
})
export class ServiceRequestCancellationComponent implements IBaseDialog, OnInit {
  cancellationTypes = [
    {
      display: $localize`Immediate`,
      value: 'immediate'
    },
    {
      display: $localize`On service due date`,
      value: 'cycleend'
    },
  ];
  requestCancellationForm = this.formBuilder.group({
    reason: ['', Validators.required],
    cancellation_type: ['immediate', Validators.required],
  });
  dialogTitle = $localize`Request service cancellation`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Request cancellation`,
      primary: true,
      callback: () => this.requestCancellation(),
    }),
  ];
  dialogForm = this.requestCancellationForm;
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<ServiceRequestCancellationComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { service: IServiceModel },
    private servicesApi: ServicesApiService,
    private notificationService: NotificationService,
    private formBuilder: UntypedFormBuilder,
  ) {
  }

  ngOnInit() {
  }

  requestCancellation() {
    if (!this.requestCancellationForm.valid) {
      return;
    }

    this.loading = true;
    this.servicesApi.cancel(
      this.data.service.id, this.requestCancellationForm.value,
    ).subscribe(() => {
      this.notificationService.showMessage($localize`Service cancellation requested`);
      this.dialogRef.close($localize`Service cancellation requested`);
    },()=>{
      this.notificationService.showMessage($localize`Failed to request service cancellation, please contact support.`);
    }).add(() => {
      this.loading = false;
    });
  }
}
