import { animate, state, style, transition, trigger } from '@angular/animations';
import { ChangeDetectionStrategy, Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { ApplicationProcess } from '@core/application';
import { ConfirmModalData, UiConfirmModalComponent, UiModalService } from '@ui/modal';

@Component({
  selector: 'shell-process-tab',
  templateUrl: './process-tab.component.html',
  styleUrls: ['./process-tab.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [
    trigger('slideIn', [
      state(
        'start',
        style({
          marginRight: '5rem',
        })
      ),
      state(
        'end',
        style({
          marginRight: '1.875rem',
        })
      ),
      transition('start => end', [animate('200ms ease-in')]),
    ]),
  ],
})
export class ShellProcessTabComponent implements OnInit {
  @ViewChild('tab', { static: true }) tab: ElementRef<HTMLButtonElement>;

  @Input()
  process: ApplicationProcess;

  @Input()
  isActive: boolean;

  @Output()
  activateProcess = new EventEmitter<number>();

  @Output()
  processAction = new EventEmitter<ApplicationProcess>();

  @Output()
  closeProcess = new EventEmitter<number>();

  animate = false;

  constructor(private readonly _modal: UiModalService) {}

  ngOnInit() {}

  slideIntoView() {
    this.tab.nativeElement.scrollIntoView();
  }

  triggerAnimation() {
    this.animate = true;
  }

  slideAnimationDone(animationEnd: AnimationEvent) {
    if (this.isActive) {
      this.tab.nativeElement.scrollIntoView({ behavior: 'smooth' });
    }
    this.animate = false;
  }

  onTabClick() {
    this.activateProcess.emit(this.process.id);
    this.tab.nativeElement.scrollIntoView({ behavior: 'smooth' });
  }

  onProcessAction(e: Event) {
    e.preventDefault();
    e.stopPropagation();
    this.processAction.emit(this.process);
  }

  checkCloseProcess() {
    if (this.process.confirmClosing) {
      this._modal
        .open({
          content: UiConfirmModalComponent,
          title: 'Möchten Sie den Vorgang wirklich schließen?',
          data: {
            message: this.process.name,
            confirmLabel: 'Schließen',
            rejectLabel: 'Abbrechen',
          } as ConfirmModalData,
        })
        .afterClosed$.subscribe((result) => {
          if (result.data) {
            this.closeProcess.emit(this.process.id);
          }
        });
    } else {
      this.closeProcess.emit(this.process.id);
    }
  }
}
