import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
import { InvoicesApiService } from '@fleio-api/billing/invoices/invoices-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IInvoiceModel } from '@fleio-api/billing/model/invoice.model';
import { UntypedFormBuilder, Validators } from '@angular/forms';
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-invoice-delete-dialog',
  templateUrl: './invoice-send-notification-dialog.component.html',
  styleUrls: ['./invoice-send-notification-dialog.component.scss']
})
export class InvoiceSendNotificationDialogComponent implements IBaseDialog, OnInit {
  invoice: IInvoiceModel;
  templates: [{
    id: FleioId;
    name: string;
    title: string;
  }];
  sendNotificationForm = this.formBuilder.group({
    templateId: ['', Validators.required],
  });
  dialogTitle = $localize`Send invoice related notification`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Send notification`,
      primary: true,
      callback: () => this.sendNotification(),
    }),
  ];
  dialogForm = this.sendNotificationForm;
  loading: boolean;


  constructor(
    public dialogRef: MatDialogRef<InvoiceSendNotificationDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      invoiceID: FleioId;
    },
    private invoicesApiService: InvoicesApiService,
    private notificationService: NotificationService,
    private formBuilder: UntypedFormBuilder,
  ) {
  }

  ngOnInit() {
    if (this.data && this.data.invoiceID) {
      this.loading = true;
      this.invoicesApiService.getMessageTemplates(this.data.invoiceID).subscribe(response => {
        this.templates = response.templates;
      }).add(() => {
        this.loading = false;
      });
    }
  }

  sendNotification() {
    if (!this.sendNotificationForm.valid) {
      return;
    }

    const formValue = this.sendNotificationForm.value;

    this.loading = true;
    this.invoicesApiService.sendNotification(this.data.invoiceID, formValue.templateId).subscribe({
      next: () => {
        this.dialogRef.close(true);
        this.notificationService.showMessage($localize`Notification sent.`);
      },
      error: () => {
        this.notificationService.showMessage($localize`Failed to send notification.`);
        this.dialogRef.close(false);
      }
    }).add(() => {
      this.loading = false;
    });
  }
}
