import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { ITicketModel } from '@fleio-api/plugins/tickets/model/ticket.model';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { NotificationService } from '@shared/ui-api/notification.service';
import { TicketsApiService } from '@fleio-api/plugins/tickets/tickets-api.service';
import { map } from 'rxjs/operators';
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 { Observable } from 'rxjs';

@Component({
  selector: 'app-ticket-merge-dialog',
  templateUrl: './ticket-merge-dialog.component.html',
  styleUrls: ['./ticket-merge-dialog.component.scss']
})
export class TicketMergeDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  backendErrors: Record<string, unknown> = {};
  ticketMergeForm: UntypedFormGroup = this.formBuilder.group({
    source_ticket: ['', Validators.required],
  });
  dialogTitle = $localize`Merge a ticket into #${this.data?.ticket?.id}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Merge ticket`,
      primary: true,
      callback: () => this.mergeTicket(),
    }),
  ];
  dialogForm = this.ticketMergeForm;
  loading = false;
  fieldRequiredTxt = $localize`This field is required!`;
  ticketAutocompleteSwitchMap: (search: string) => Observable<any>;
  placeholderUnselected = $localize`Select ticket ...`;
  placeholderSelected = $localize`Ticket`;

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

  displayTicketFn(ticket: ITicketModel) {
    if (ticket) {
      return `#${ticket.id} - ${ticket.title}`;
    }
    return '';
  }

  ngOnInit() {
    if (this.data?.ticket) {
      this.ticketAutocompleteSwitchMap = (search) => this.ticketsApiService.getTicketsForMerge(this.data.ticket.id, search).pipe(map(
          tickets => tickets.objects
        ));
    }
  }

  mergeTicket() {
    const value = this.ticketMergeForm.value;
    this.loading = true;
    this.ticketsApiService.mergeTicket(
      this.data.ticket.id, value.source_ticket.id,
    ).subscribe(() => {
      this.notificationService.showMessage($localize`Ticket merged successfully.`);
      this.dialogRef.close($localize`Ticket merged successfully.`);
    }, error => {
      this.notificationService.showMessage(error.error.detail);
    }).add(() => {
      this.loading = false;
    });
  }
}
