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 ButtonVariant = 'filled' | 'tonal' | 'outlined';
export type ButtonSize = 'small' | 'medium' | 'large';
export type IconPosition = 'left' | 'right';

@Component({
  selector: 'ui-button',
  standalone: true,
  imports: [CommonModule, FontAwesomeModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <button
      [class]="buttonClasses"
      [disabled]="disabled || loading"
      [type]="type"
      (click)="handleClick($event)"
    >
      @if (loading) {
        <div class="button-loader">
          <div class="button-spinner"></div>
        </div>
      } @else {
        <div class="button-content">
          @if (icon && iconPosition === 'left') {
            <fa-icon [icon]="icon" class="button-icon button-icon--left"></fa-icon>
          }
          <span class="button-text">
            <ng-content></ng-content>
          </span>
          @if (icon && iconPosition === 'right') {
            <fa-icon [icon]="icon" class="button-icon button-icon--right"></fa-icon>
          }
        </div>
      }
    </button>
  `,
  styleUrl: './button.component.scss'
})
export class ButtonComponent {
  @Input() variant: ButtonVariant = 'filled';
  @Input() size: ButtonSize = 'medium';
  @Input() disabled: boolean = false;
  @Input() loading: boolean = false;
  @Input() type: 'button' | 'submit' | 'reset' = 'button';
  @Input() fullWidth: boolean = false;
  @Input() class: string = '';
  @Input() icon?: IconDefinition;
  @Input() iconPosition: IconPosition = 'left';

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

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

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