import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ITicketReplyModel } from '@fleio-api/plugins/tickets/model/ticket-reply.model';
import { ConfigService } from '@shared/config/config.service';
import { TicketUpdatesApiService } from '@fleio-api/plugins/tickets/ticket-updates-api.service';
import { TicketNotesApiService } from '@fleio-api/plugins/tickets/ticket-notes-api.service';
import { ThemingService } from '@shared/ui/theming/theming.service';
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';
import { FormErrorsComponent } from '@shared/error-handling/form-errors/form-errors.component';

@Component({
  selector: 'app-ticket-edit-message-dialog',
  templateUrl: './ticket-edit-message-dialog.component.html',
  styleUrls: ['./ticket-edit-message-dialog.component.scss']
})
export class TicketEditMessageDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors: FormErrorsComponent;
  backendErrors: Record<string, unknown> = {};
  editTicketMessageForm: UntypedFormGroup = this.formBuilder.group({
    reply_text: ['', Validators.required]
  });
  dialogTitle = $localize`Edit message`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Save message`,
      primary: true,
      callback: () => this.save(),
    }),
  ];
  dialogForm = this.editTicketMessageForm;
  loading = false;
  tinyMCEOptions = null;

  constructor(
    public dialogRef: MatDialogRef<TicketEditMessageDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      ticketReply: ITicketReplyModel;
    },
    private config: ConfigService,
    private formBuilder: UntypedFormBuilder,
    private ticketUpdatesApiService: TicketUpdatesApiService,
    private ticketNotesApiService: TicketNotesApiService,
    private themingService: ThemingService,
  ) {
  }


  ngOnInit() {
    if (this.config && this.config.current) {
      this.tinyMCEOptions = this.themingService.getTinyMceOptions();
    }
    if (this.data && this.data.ticketReply) {
      this.loading = true;
      if (this.data.ticketReply.message_type === 'ticketupdate') {
        this.ticketUpdatesApiService.get(this.data.ticketReply.id).subscribe(reply => {
          this.editTicketMessageForm.controls.reply_text.setValue(reply.message);
          this.loading = false;
        });
      } else {
        this.ticketNotesApiService.get(this.data.ticketReply.id).subscribe(reply => {
          this.editTicketMessageForm.controls.reply_text.setValue(reply.message);
          this.loading = false;
        });
      }
    }
  }

  handleTinyKeyDown(event: any) {
    if (event && event.event && event.event.ctrlKey && event.event.keyCode === 13) {
      event.event.preventDefault();
      this.save();
    }
  }

  save() {
    const ticketReply = this.data.ticketReply;
    const value = this.editTicketMessageForm.value;
    if (ticketReply.message_type === 'ticketupdate') {
      this.loading = true;
      // @ts-ignore
      this.ticketUpdatesApiService.update(ticketReply.id, {reply_text: value.reply_text})
        .subscribe({
          next: () => {
            this.dialogRef.close(true);
          }, error: error => {
            this.backendErrors = error.error;
            this.formErrors.setBackendErrors(error.error);
          }
        }).add(() => {
        this.loading = false;
      });
    } else {
      this.loading = true;
      // @ts-ignore
      this.ticketNotesApiService.update(ticketReply.id, {note_text: value.reply_text})
        .subscribe({
          next: () => {
            this.dialogRef.close(true);
          }, error: error => {
            this.backendErrors = error.error;
            this.formErrors.setBackendErrors(error.error);
          }
        }).add(() => {
        this.loading = false;
      });
    }
  }
}
