import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { IconDefinition } from '@fortawesome/fontawesome-svg-core';

export type IconButtonVariant = 'filled' | 'tonal' | 'outlined';
export type IconButtonSize = 'small' | 'medium' | 'large';

@Component({
  selector: 'ui-icon-button',
  standalone: true,
  imports: [CommonModule, FontAwesomeModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <button
      [class]="buttonClasses"
      [disabled]="disabled || loading"
      [type]="type"
      [attr.aria-label]="ariaLabel"
      [attr.aria-pressed]="pressed"
      [attr.title]="title"
      (click)="handleClick($event)"
    >
      @if (loading) {
        <div class="icon-button-loader">
          <div class="icon-button-spinner"></div>
        </div>
      } @else {
        <fa-icon [icon]="icon" class="icon-button-icon"></fa-icon>
      }
    </button>
  `,
  styleUrl: './icon-button.component.scss'
})
export class IconButtonComponent {
  @Input({ required: true }) icon!: IconDefinition;
  @Input() variant: IconButtonVariant = 'filled';
  @Input() size: IconButtonSize = 'medium';
  @Input() disabled: boolean = false;
  @Input() loading: boolean = false;
  @Input() pressed: boolean = false;
  @Input() type: 'button' | 'submit' | 'reset' = 'button';
  @Input() class: string = '';
  @Input() ariaLabel: string = '';
  @Input() title: string = '';

  @Output() clicked = new EventEmitter<Event>();

  get buttonClasses(): string {
    return [
      'ui-icon-button',
      `ui-icon-button--${this.variant}`,
      `ui-icon-button--${this.size}`,
      this.disabled ? 'ui-icon-button--disabled' : '',
      this.loading ? 'ui-icon-button--loading' : '',
      this.pressed ? 'ui-icon-button--pressed' : '',
      this.class
    ].filter(Boolean).join(' ');
  }

  handleClick(event: Event): void {
    if (!this.disabled && !this.loading) {
      this.clicked.emit(event);
    }
  }
}