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 { NotificationService } from '@shared/ui-api/notification.service';
import { ITicketModel } from '@fleio-api/plugins/tickets/model/ticket.model';
import { map } from 'rxjs/operators';
import { TicketsApiService } from '@fleio-api/plugins/tickets/tickets-api.service';
import { TicketLinkingApiService } from '@fleio-api/plugins/tickets/ticket-linking-api.service';
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-link-dialog',
  templateUrl: './ticket-link-dialog.component.html',
  styleUrls: ['./ticket-link-dialog.component.scss']
})
export class TicketLinkDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  backendErrors: Record<string, unknown> = {};
  linkTicketForm: UntypedFormGroup = this.formBuilder.group({
    linked_ticket: ['', Validators.required],
    symmetrical: [false, Validators.required]
  });
  dialogTitle = $localize`Link a ticket`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Link ticket`,
      primary: true,
      callback: () => this.linkTicket(),
    }),
  ];
  dialogForm = this.linkTicketForm;
  loading = false;
  fieldRequiredTxt = $localize`This field is required!`;
  ticketAutocompleteSwitchMap: (search: string) => Observable<any>;
  placeholderUnselected = $localize`Select ticket ...`;
  placeholderSelected = $localize`Ticket`;

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

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

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

  linkTicket() {
    if (this.linkTicketForm.invalid) {
      return;
    }
    const value = this.linkTicketForm.value;
    this.loading = true;
    this.ticketLinkingApiService.create({
      ticket: this.data.ticket.id,
      linked_ticket: value.linked_ticket.id,
      symmetrical: value.symmetrical,
    }).subscribe(result => {
      this.dialogRef.close($localize`Ticket linking done successfully.`);
    }, error => {
      this.formErrors.setBackendErrors(error.error);
    }).add(() => {
      this.loading = false;
    });
  }
}
