import { Component, Input, Output, EventEmitter, HostListener } from '@angular/core';
import { NbpBaseComponent, NbpStyle, NbpSize, INbpButton } from '@isp/xdce-widget/base';
import { ISidePopup, ISidePopupButton } from './nbp-fid-side-popup.interfaces';

@Component({
  selector: 'nbp-fid-side-popup',
  templateUrl: './nbp-fid-side-popup.component.html',
  styleUrls: ['./nbp-fid-side-popup.component.scss']
})
export class NbpFidSidePopupComponent extends NbpBaseComponent implements ISidePopup {
  private static counter = 0;
  readonly id = `side-popup-${NbpFidSidePopupComponent.counter++}`;

  _style = NbpStyle;
  _size = NbpSize;

  private _isOpen = false;
  private _nbpTitle?: string;
  private _nbpSize: NbpSize = NbpSize.MD;
  private _nbpStyle: NbpStyle = NbpStyle.DEFAULT;
  private _nbpButtons: ISidePopupButton[] = [];
  private _hideOverlay = false;
  private _hideCloseButton = false;

  @Input()
  set hideOverlay(value: boolean) {
    this._hideOverlay = value;
  }
  get hideOverlay(): boolean {
    return this._hideOverlay;
  }

  @Input()
  set hideCloseButton(value: boolean) {
    this._hideCloseButton = value;
  }
  get hideCloseButton(): boolean {
    return this._hideCloseButton;
  }

  @Input()
  set isOpen(value: boolean) {
    this._isOpen = value;
  }
  get isOpen(): boolean {
    return this._isOpen;
  }

  @Input()
  set nbpTitle(value: string) {
    this._nbpTitle = value;
  }
  get nbpTitle(): string {
    return this._nbpTitle;
  }

  @Input()
  set nbpSize(value: NbpSize) {
    this._nbpSize = value;
  }
  get nbpSize(): NbpSize {
    return this._nbpSize;
  }

  @Input()
  set nbpStyle(value: NbpStyle) {
    this._nbpStyle = value;
  }
  get nbpStyle(): NbpStyle {
    return this._nbpStyle;
  }

  @Input()
  set nbpButtons(value: ISidePopupButton[]) {
    this._nbpButtons = value;
  }
  get nbpButtons(): ISidePopupButton[] {
    return this._nbpButtons;
  }

  @Output() isOpenChange = new EventEmitter<boolean>();
  @Output() nbpOnButtonClick = new EventEmitter<INbpButton>();
  @Output() closed = new EventEmitter<void>();

  @HostListener('document:keydown.escape')
  handleEscape() {
    if (this.isOpen) {
      this.close();
    }
  }

  close() {
    this.isOpen = false;
    this.isOpenChange.emit(false);
    this.closed.emit();
  }

  onOverlayClick(event: MouseEvent) {
    if (event.target === event.currentTarget) {
      this.close();
    }
  }

  onButtonClick(button: ISidePopupButton) {
    if (!button.disabled) {
      this.nbpOnButtonClick.emit(button);
    }
  }
}
