import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { ITicketSignatureModel } from '@fleio-api/plugins/tickets/model/ticket-signature.model';
import { ConfigService } from '@shared/config/config.service';
import { UntypedFormArray, UntypedFormBuilder } from '@angular/forms';
import { IAction } from '@objects-view/interfaces/actions/action';
import { EMPTY, Observable, of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { TicketsSignaturesApiService } from '@fleio-api/plugins/tickets/tickets-signatures-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { AddSignatureDialogComponent } from './add-signature-dialog/add-signature-dialog.component';
import { MatDialog } from '@angular/material/dialog';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
import { ThemingService } from '@shared/ui/theming/theming.service';
import { IYesNoDialogResult } from '@shared/ui-api/interfaces/yes-no-dialog-result';

@Component({
  selector: 'app-ticket-edit-signatures-form',
  templateUrl: './ticket-edit-signatures-form.component.html',
  styleUrls: ['./ticket-edit-signatures-form.component.scss']
})
export class TicketEditSignaturesFormComponent extends DetailsFormBase<any> implements OnInit {
  signaturesForm = this.initBasicForm();
  signatures: Array<ITicketSignatureModel> = [];
  tinyMCEOptions: any;

  initBasicForm() {
    return this.formBuilder.group({
      objects: this.formBuilder.array([])
    });
  }

  initSignatureObj() {
    return this.formBuilder.group({
      id: [''],
      content: [''],
      user: [null],
      department: [null],
      department_display: ['']
    });
  }

  constructor(
    private formBuilder: UntypedFormBuilder,
    private config: ConfigService,
    private ticketsSignaturesApiService: TicketsSignaturesApiService,
    private notificationService: NotificationService,
    private matDialog: MatDialog,
    private themingService: ThemingService,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
  ) {
    super(ngZone, changeDetectorRef, config);
  }

  public get signaturesObjects() {
    return this.signaturesForm.get('objects') as UntypedFormArray;
  }

  protected refreshData() {
    super.refreshData();
    this.ticketsSignaturesApiService.getSignaturesForCurrentUser().subscribe(result => {
      this.objectController.object = result as any;
      this.initFormData();
    });
  }

  addGlobalSignature() {
    const dialogResult$ = this.notificationService.confirmDialog({
      title: $localize`Add global signature?`,
      message: $localize`This will add the global signature`,
    });
    dialogResult$.subscribe((dialogResult: IYesNoDialogResult) => {
      if (dialogResult?.button === 'yes') {
        this.ticketsSignaturesApiService.addGlobalSignature().subscribe({
          next: () => {
            this.notificationService.showMessage($localize`Successfully added global signature.`);
            this.refreshData();
          }, error: () => {
            this.notificationService.showMessage($localize`Could not add global signature.`);
          }
        });
      }
    });
  }

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


  private signaturesActions(action: IAction): Observable<IActionResult> {
    if (action?.internalName === 'Add signature') {
      if (this.signatures.length === 0) {
        this.addGlobalSignature();
        return of(null);
      }
      this.matDialog.open(
        AddSignatureDialogComponent
      ).afterClosed().subscribe(result => {
        if (result === true) {
          this.refreshData();
        }
      });
      return of(null);
    }

    const value = this.signaturesForm.value;

    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return EMPTY;
    }

    this.ticketsSignaturesApiService.saveSignatures(value).subscribe({
      next: () => {
        this.refreshData();
        this.notificationService.showMessage($localize`Successfully saved signatures.`);
      }, error: error => {
        if (error.error) {
          this.setErrors(error.error);
        }
        this.notificationService.showMessage($localize`Failed to save signatures`);
      }
    });

    return of(null);
  }

  deleteSignature(id: FleioId) {
    const dialogResult$ = this.notificationService.confirmDialog({
      title: $localize`Delete signature?`,
      message: $localize`This will delete the signature`,
    });
    dialogResult$.subscribe(dialogResult => {
      if (dialogResult?.button === 'yes') {
        this.ticketsSignaturesApiService.delete(id).subscribe({
          next: () => {
            this.notificationService.showMessage($localize`Successfully deleted signature.`);
            this.refreshData();
          }, error: () => {
            this.notificationService.showMessage($localize`Could not delete signature.`);
          }
        });
      }
    });
  }

  initFormData() {
    this.signaturesForm = this.initBasicForm();
    if (this.object) {
      this.signatures = this.object.objects;
      this.primaryAction.disabled = !this.signatures.length;
      let i = 0;
      while (i < this.signatures.length) {
        this.signaturesObjects.push(this.initSignatureObj());
        i++;
      }
      if (this.object && this.object.objects && this.object.objects.length) {
        this.signaturesForm.patchValue(this.object);
      }
    }
  }

  ngOnInit(): void {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = (action: IAction) => this.signaturesActions(action);
    }
    this.initFormData();
    if (this.config && this.config.current) {
      this.tinyMCEOptions = this.themingService.getTinyMceOptions();
    }
  }

}
