import {
  ChangeDetectionStrategy,
  Component,
  computed,
  input,
  ViewEncapsulation,
} from '@angular/core';
import { IconButtonColor, IconButtonSize } from './types';
import { NgIconComponent, provideIcons } from '@ng-icons/core';
import { isaLoading } from '@isa/icons';

/**
 * A reusable button component that displays an icon with configurable appearance and behavior.
 * Supports different sizes, colors, loading states, and accessibility features.
 *
 * @example
 * ```html
 * <ui-icon-button
 *   name="isaActionEdit"
 *   color="primary"
 *   size="large"
 *   [pending]="isLoading"
 *   [disabled]="isDisabled">
 * </ui-icon-button>
 * ```
 */
@Component({
  selector: 'ui-icon-button, [uiIconButton]',
  templateUrl: './icon-button.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  standalone: true,
  imports: [NgIconComponent],
  providers: [provideIcons({ isaLoading })],
  host: {
    '[class]': "['ui-icon-button', sizeClass(), colorClass(), disabledClass()]",
    '[tabindex]': 'tabIndex()',
    '[attr.aria-disabled]': 'disabled()',
    '[attr.aria-label]': 'name()',
    '[attr.aria-busy]': 'pending()',
    '[attr.role]': 'pending() ? "progressbar" : "button"',
  },
})
export class IconButtonComponent {
  /** The name of the icon to display */
  name = input<string>();

  /** The size of the button: 'medium' or 'large' */
  size = input<IconButtonSize>('large');

  /** Computed class based on the current size */
  sizeClass = computed(() => `ui-icon-button__${this.size()}`);

  /** The color scheme of the button */
  color = input<IconButtonColor>('primary');

  /** Computed class based on the current color */
  colorClass = computed(() => `ui-icon-button__${this.color()}`);

  /** Whether the button is in a loading state */
  pending = input<boolean>(false);

  /** The tab index for keyboard navigation */
  tabIndex = input<number>(0);

  /** Whether the button is disabled */
  disabled = input<boolean>(false);

  /** Computed CSS class for the disabled state */
  disabledClass = computed(() => (this.disabled() ? 'disabled' : ''));

  /** Computed icon name based on pending state */
  iconName = computed(() => {
    return this.pending() ? 'isaLoading' : this.name();
  });

  /** Computed icon size based on button size */
  iconSize = computed(() => {
    const size = this.size();

    if (size === 'small') return `1rem`;
    if (size === 'medium') return `1.25rem`;
    if (size === 'large') return `1.5rem`;

    return `1.25rem`;
  });
}
