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 { ConfigService } from '@shared/config/config.service';
import { ThemingService } from '@shared/ui/theming/theming.service';
import { TicketsApiService } from '@fleio-api/plugins/tickets/tickets-api.service';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
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';
import { FormErrorsComponent } from '@shared/error-handling/form-errors/form-errors.component';

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

  constructor(
    public dialogRef: MatDialogRef<TicketAddNoteDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      ticketID: FleioId;
    },
    private config: ConfigService,
    private formBuilder: UntypedFormBuilder,
    private ticketsApiService: TicketsApiService,
    private themingService: ThemingService,
  ) {
  }

  ngOnInit(): void {
    if (this.config && this.config.current) {
      this.tinyMCEOptions = this.themingService.getTinyMceOptions();
    }
  }

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

  save() {
    const value = this.addTicketNoteForm.value;
    this.loading = true;
    this.ticketsApiService.addNote(this.data.ticketID, value.note_text, null).subscribe({
      next: () => {
        this.dialogRef.close(true);
      },
      error: (error) => {
        this.backendErrors = error.error;
        this.formErrors.setBackendErrors(error.error);
      }
    }).add(() => {
      this.loading = false;
    });
  }

}
