import { CommonModule } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  EventEmitter,
  Input,
  Output,
  ViewEncapsulation
} from '@angular/core';
import { ThemeComponentsVariants } from '../../models/theme-variant.model';
import { IconButtonComponent } from '../icon-button/icon-button.component';
import { TagSize } from './tag.model';

@Component({
  selector: 'nj-tag',
  templateUrl: './tag.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  standalone: true,
  imports: [IconButtonComponent, CommonModule]
})
export class TagComponent {
  private readonly tagClassName = 'nj-tag';

  /**
   * Tag variant
   *
   * @default `grey`
   */
  @Input() variant?: ThemeComponentsVariants;

  /**
   * Tag size
   */
  @Input() size?: TagSize = 'md';

  /**
   * Tag iconName
   */
  @Input() iconName?: string;

  /**
   * Tag href. If set, tag renders a link
   */
  @Input() href?: string;

  /**
   * target of link tag
   */
  @Input() target?: string;

  /**
   * If set, tag renders a button
   */
  @Input() isClickable?: boolean;

  /**
   * Whether tag can be closed
   */
  @Input() isClosable?: boolean;

  /**
   * Whether tag should remove himself when close is clicked
   */
  @Input() shouldAutoDestruct = true;

  /**
   * Label for the close button, if present
   * @example "Remove [tag name]"
   */
  @Input() closeLabel?: string;

  /**
   * Whether tag is disabled
   */
  @Input() isDisabled?: boolean;

  /**
   * Whether tag has custom icon
   */
  @Input() hasCustomIcon?: boolean;

  /**
   * Output event when clickable tag is clicked
   */
  @Output() tagClick = new EventEmitter<MouseEvent>();

  /**
   * Output event when tag is closed. Focus must be set to either previous tag, next tag or any relevant element.
   */
  @Output() closeClick = new EventEmitter<MouseEvent>();

  constructor(private el: ElementRef) {}

  /**
   * @ignore
   */
  getTagVariantClass(): string {
    if (!this.variant) {
      return '';
    }
    return `${this.tagClassName}--${this.variant}`;
  }

  /**
   * @ignore
   */
  getTagSizeClass(): string {
    if (!this.size || this.size === 'md') {
      return '';
    }
    return `${this.tagClassName}--${this.size}`;
  }

  /**
   * @ignore
   */
  getTagDisabledClass(): string {
    if (!this.isDisabled) {
      return '';
    }
    return `${this.tagClassName}--disabled`;
  }

  /**
   * @ignore
   */
  removeTag(event: MouseEvent) {
    event?.preventDefault();
    event?.stopImmediatePropagation();
    if (this.shouldAutoDestruct) {
      this.el?.nativeElement?.remove();
    }
    this.closeClick.emit(event);
  }

  focusIconButton() {
    this.el?.nativeElement?.querySelector('nj-icon-button button')?.focus();
  }
}
