import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ITicketModel } from '@fleio-api/plugins/tickets/model/ticket.model';
import { NotificationService } from '@shared/ui-api/notification.service';
import { TicketsApiService } from '@fleio-api/plugins/tickets/tickets-api.service';
import { MessageTemplatesApiService } from '@fleio-api/message-templates/message-templates-api.service';
import { IMessageTemplateModel } from '@fleio-api/message-templates/model/message-template.model';
import { TicketDepartmentsApiService } from '@fleio-api/plugins/tickets/ticket-departments-api.service';

@Component({
  selector: 'app-close-ticket-dialog',
  templateUrl: './close-ticket-dialog.component.html',
  styleUrls: ['./close-ticket-dialog.component.scss']
})
export class CloseTicketDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  backendErrors: Record<string, unknown> = {};
  closeTicketForm: UntypedFormGroup = this.formBuilder.group({
    send_notification: [true],
    end_user_custom_template_name: ['ticket.closed'],
  });
  dialogTitle = $localize`Close ticket #${this.data?.ticket?.id} ${this.data?.ticket?.title}?`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Close ticket`,
      primary: true,
      callback: () => this.closeTicket(),
    }),
  ];
  dialogForm = this.closeTicketForm;
  loading = false;
  templates = [];
  selectedMessageTemplate: IMessageTemplateModel;
  formattedTemplate = null;
  hideOptions = false;

  constructor(
    public dialogRef: MatDialogRef<CloseTicketDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { ticket: ITicketModel },
    private notificationService: NotificationService,
    private formBuilder: UntypedFormBuilder,
    public ticketsApiService: TicketsApiService,
    private messageTemplatesApiService: MessageTemplatesApiService,
    private ticketDepartmentsApiService: TicketDepartmentsApiService,
  ) {
  }

  refreshTemplate() {
    this.loading = true;
    this.selectedMessageTemplate = this.templates.find(
      (template) => template.name === this.closeTicketForm.controls.end_user_custom_template_name.value
    );
    this.ticketsApiService.getEnduserFormattedTemplate(this.data.ticket.id, this.selectedMessageTemplate.name).subscribe(
      formattedTemplate => {
      this.formattedTemplate = formattedTemplate;
    }).add(() => {
      this.loading = false;
    });
  }

  ngOnInit() {
    if (this.data?.ticket) {
      this.loading = true;
      this.ticketDepartmentsApiService.get(this.data.ticket.department).subscribe(department => {
        if (department.notification_to_user_on_ticket_closed) {
          this.messageTemplatesApiService.list({
            page_size: 10000000,
            filtering: 'category__name:ticket',
          }).subscribe(value => {
            this.templates = value.objects;
            this.refreshTemplate();
          });
        } else {
          this.hideOptions = true;
          this.loading = false;
        }
      });
    }
    this.closeTicketForm.controls.end_user_custom_template_name.valueChanges.subscribe(templateName => {
      this.formattedTemplate = null;
      this.refreshTemplate();
    });
  }

  closeTicket() {
    const value = this.closeTicketForm.value;
    this.loading = true;
    this.ticketsApiService.closeTicket(
      this.data.ticket.id,
      value.send_notification,
      value.end_user_custom_template_name,
    ).subscribe({
      next: () => {
        this.notificationService.showMessage($localize`Ticket closed.`);
        this.dialogRef.close($localize`Ticket closed.`);
      }, error: error => {
        this.backendErrors = error?.error;
        this.formErrors.setBackendErrors(this.backendErrors);
      }
    }).add(() => {
      this.loading = false;
    });
  }
}
