import { CommonModule } from '@angular/common';
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ContentChild,
  EventEmitter,
  HostBinding,
  inject,
  Input,
  Output,
  ViewEncapsulation
} from '@angular/core';
import { ButtonComponent } from '../button/button.component';
import { SidepanelLayoutPanelDirective } from './directives/sidepanel-layout-panel.directive';
import { sidePanelLayoutAnimation } from './sidepanel-layout.animations';

@Component({
  selector: 'nj-sidepanel-layout',
  templateUrl: 'sidepanel-layout.component.html',
  animations: [sidePanelLayoutAnimation.panelSlideInAndOut, sidePanelLayoutAnimation.panelOpened],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  standalone: true,
  imports: [ButtonComponent, SidepanelLayoutPanelDirective, CommonModule]
})
export class SidepanelLayoutComponent {
  private cdr = inject(ChangeDetectorRef);

  protected _isPanelDisplayed = true;
  protected _animationParams = {};

  @HostBinding('class') private staticClass = 'nj-sidepanel-layout';

  /**
   * Whether the panel animation should be disabled
   */
  @Input()
  set isAnimationDisabled(value: boolean) {
    this._animationParams = value && { animationDuration: '0ms' };
  }

  /**
   * Whether the panel should be displayed beside or over the content
   */
  @HostBinding('class.nj-sidepanel-layout--over-content')
  @Input()
  isOverContent = false;

  /**
   * Emit when sidepanel visibility state change
   */
  @Output() sidepanelVisibilityChange = new EventEmitter<boolean>();

  @ContentChild(SidepanelLayoutPanelDirective) protected panel?: SidepanelLayoutPanelDirective;

  /**
   * Show sidepanel
   */
  showPanel() {
    this.changePanelVisibility(true);
  }

  /**
   * Hide sidepanel
   */
  hidePanel() {
    this.changePanelVisibility(false);
  }

  private changePanelVisibility(isPanelDisplayed: boolean) {
    if (isPanelDisplayed === this._isPanelDisplayed) {
      return;
    }
    this._isPanelDisplayed = isPanelDisplayed;
    this.sidepanelVisibilityChange.emit(isPanelDisplayed);
    this.cdr.markForCheck();
  }
}
