import { DialogRef } from '@angular/cdk/dialog';
import { CommonModule } from '@angular/common';
import {
  AfterViewInit,
  ChangeDetectionStrategy,
  Component,
  EventEmitter,
  Input,
  Optional,
  Output,
  ViewEncapsulation
} from '@angular/core';
import { IconButtonComponent } from '../icon-button/icon-button.component';
import { modalAnimation } from './modal.animations';

@Component({
  selector: 'nj-modal',
  templateUrl: './modal.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  animations: [modalAnimation.modal],
  standalone: true,
  imports: [IconButtonComponent, CommonModule]
})
export class ModalComponent implements AfterViewInit {
  /**
   * Whether modal has close icon or not
   */
  @Input() hasCloseIcon = false;

  /**
   * Label for the close button
   * @example "Close"
   */
  @Input() closeLabel?: string;

  /**
   * Whether modal is vertically centered
   */
  @Input() isVerticallyCentered = true;

  /**
   * Id of the modal. The title id will be based on this.
   */
  @Input() modalId: string;

  /**
   * Emits void event when modal is closed via the close icon
   */
  @Output() closed = new EventEmitter<void>();

  /**
   * @param dialogRef refers to `@angular/cdk` DialogRef
   */
  constructor(@Optional() public dialogRef: DialogRef) {
    const backdropElement = this.dialogRef?.overlayRef?.backdropElement;
    // Add fluid backdrop background color to dialog overlay
    if (backdropElement) {
      backdropElement.style.backgroundColor = 'var(--nj-component-backdrop-color-background)';
    }
  }

  get titleId(): string {
    return `${this.modalId}-title`;
  }

  ngAfterViewInit() {
    // Manually set the `aria-labelledby` attribute on the modal
    setTimeout(() => {
      // @ts-expect-error
      this.dialogRef?.containerInstance._elementRef.nativeElement.setAttribute('aria-labelledby', this.titleId);
    });
  }

  /**
   * Emits closed event and calls dialogRef.close()
   */
  public closeModal() {
    this.closed?.emit();
    this.dialogRef?.close();
  }
}
