import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
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-pricing-plan-delete',
  templateUrl: './service-enable-billing.component.html',
  styleUrls: ['./service-enable-billing.component.scss']
})
export class ServiceEnableBillingComponent implements IBaseDialog, OnInit {
  newCycleStartOptions = [{
    display: $localize`After last cycle end`,
    value: 'after_last_cycle_end'
  }, {
    display: $localize`Last cycle start`,
    value: 'last_cycle_start'
  }, {
    display: $localize`Today`,
    value: 'today'
  }];
  newCycleStartOptionsForm: UntypedFormGroup = new UntypedFormGroup({
    newCycleStart: new UntypedFormControl('after_last_cycle_end', Validators.required),
  });
  dialogTitle = $localize`Enable billing for service ${this.data?.service?.id}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Enable service billing`,
      primary: true,
      callback: () => this.enableServiceBilling(),
    }),
  ];
  dialogForm = this.newCycleStartOptionsForm;

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

  ngOnInit() {
  }

  enableServiceBilling() {
    this.servicesApi.enableBilling(
      this.data.service.id, this.newCycleStartOptionsForm.controls.newCycleStart.value,
    ).subscribe(result => {
      if (result) {
        this.notificationService.showMessage($localize`Billing enabled`);
        this.dialogRef.close($localize`Billing enabled`);
      } else {
        this.notificationService.showMessage($localize`Failed to enable billing`);
        this.dialogRef.close(false);
      }
    });
  }
}
