import {CommonModule} from '@angular/common';
import {
  Attribute,
  ChangeDetectionStrategy,
  Component,
  HostBinding,
  inject,
  Input,
  ViewEncapsulation
} from '@angular/core';
import {RouterLink} from '@angular/router';
import {IconComponent} from '../icon/icon.component';
import {LinkIconPosition, LinkSize, LinkVariant} from './link.model';

@Component({
  selector: 'nj-link',
  templateUrl: './link.component.html',
  styleUrls: ['./link.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  standalone: true,
  imports: [IconComponent, CommonModule, RouterLink]
})
export class LinkComponent {

  @HostBinding('attr.tabindex')
  get tabIndex() {
    return this.tabIndexAttribute ?? (this.routerLink ? '-1' : undefined);
  }

  private linkClass = 'nj-link';

  private iconClass = 'nj-link-icon';

  /**
   * Link variant theme
   */
  @Input() variant: LinkVariant = 'default';

  /**
   * Link size
   */
  @Input() size: LinkSize;

  /**
   * Link target. Note when the target is `_blank`, an icon notifying the user is placed on the right of the link
   */
  @Input() target: string;

  /**
   * Link href
   */
  @Input() href: string;

  /**
   * Link rel
   */
  @Input() rel: string;

  /**
   * If link opens in a new page, an icon notifying the user is placed on the right of the link
   */
  @Input() isExternal = false;

  @Input() externalLabel: string;

  /**
   * Whether link has icon
   */
  @Input() hasIcon = false;

  /**
   * Link material icon
   */
  @Input() icon: string;

  /**
   * Whether icon is before or after text
   */
  @Input() iconPosition: LinkIconPosition = 'after';

  /**
   * Link title
   */
  @Input() title: string;

  /**
   * Link id
   */
  @Input() id: string;

  /**
   * Aria label, for accessibility reasons
   */
  @Input() ariaLabel: string;

  /**
   * Aria labelled by, for accessibility reasons
   */
  @Input() ariaLabelledBy: string;


  protected readonly routerLink? = inject(RouterLink, {self: true, optional: true});

  constructor(@Attribute('tabindex') private readonly tabIndexAttribute: string|null|undefined) {
  }

  /**
   * @ignore
   */
  isExternalLink(): boolean {
    return this.isExternal || this.target === '_blank';
  }

  /**
   * @ignore
   */
  getLinkVariantClass(): string {
    if (!this.variant || this.variant === 'default') {
      return '';
    }
    return `${this.linkClass}--${this.variant}`;
  }

  /**
   * @ignore
   */
  getIconClass(): string {
    if (!this.hasIcon && !this.isExternalLink()) {
      return '';
    }
    return this.iconClass;
  }

  /**
   * @ignore
   */
  getIconPositionClass(): string {
    if (this.iconPosition !== 'before') {
      return '';
    }
    return `${this.iconClass}--${this.iconPosition}`;
  }

  /**
   * @ignore
   */
  getSizeClass(): string {
    if (!this.size) {
      return '';
    }
    return `${this.linkClass}--${this.size}`;
  }
}
