import { CommonModule } from '@angular/common';
import { ChangeDetectionStrategy, Component, ContentChild, Input } from '@angular/core';
import { CustomIconDirective } from '../../directives/custom-icon.directive';
import { Utils } from '../../utils/utils.util';
import { IconComponent } from '../icon/icon.component';
import { BadgeEmphasis, BadgeSize, BadgeVariant } from './badge.model';

@Component({
  selector: 'nj-badge',
  templateUrl: './badge.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  imports: [CommonModule, IconComponent]
})
export class BadgeComponent {
  private badgeClassName = 'nj-badge';

  /**
   * Badge emphasis
   *
   * @default `bold`
   */
  @Input() emphasis?: BadgeEmphasis;

  /**
   * Badge variant
   *
   * @default `neutral`
   */
  @Input() variant?: BadgeVariant;

  /**
   * Badge size
   *
   * @default `md`
   */
  @Input() size?: BadgeSize;

  /**
   * Material icon name
   */
  @Input() iconName?: string;

  /**
   * Badge value
   * (when value is a string, you can pass it directly as ng-content)
   */
  @Input() value?: string | number;

  /**
   * When value is a number, you can pass a capedValue, so the displayed value will be `${capedValue}+`
   */
  @Input() capedValue?: number;

  /**
   * Badge value
   */
  @Input() isUppercase?: boolean;

  /**
   * Screen reader only unit label.
   *
   * @example
   * // read as "12 notifications"
   * <nj-badge unitLabel="notifications">12</NJBadge>
   */
  @Input() unitLabel?: string;

  @ContentChild(CustomIconDirective) protected customIcon?: CustomIconDirective;

  protected isValueDefined(): boolean {
    return !Utils.isUndefinedOrNull(this.value);
  }

  protected getFormattedValue(): string {
    if (typeof this.value === 'string') {
      return this.value;
    }

    let formattedValue = `${this.value}`;
    if (!Utils.isUndefinedOrNull(this.capedValue) && this.value > this.capedValue) {
      if (this.capedValue <= 0) {
        formattedValue = '0+';
      } else {
        formattedValue = `${this.capedValue}+`;
      }
    }
    return formattedValue;
  }

  protected getBadgeEmphasisClass(): string {
    if (!this.emphasis || this.emphasis === 'bold') {
      return '';
    }
    return `${this.badgeClassName}--${this.emphasis}`;
  }

  protected getBadgeVariantClass(): string {
    if (!this.variant || this.variant === 'neutral') {
      return '';
    }
    return `${this.badgeClassName}--${this.variant}`;
  }

  protected getBadgeSizeClass(): string {
    if (!this.size || this.size === 'md') {
      return '';
    }
    return `${this.badgeClassName}--${this.size}`;
  }

  protected getBadgeUppercaseClass(): string {
    if (!this.isUppercase) {
      return '';
    }
    return `${this.badgeClassName}--uppercase`;
  }
}
