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

export type SplitButtonVariant = 'filled' | 'tonal' | 'outlined';
export type SplitButtonSize = 'small' | 'medium' | 'large';
export type SplitButtonIconPosition = 'left' | 'right';

export interface SplitButtonMenuItem {
  label: string;
  value?: any;
  icon?: IconDefinition;
  disabled?: boolean;
}

@Component({
  selector: 'ui-split-button',
  standalone: true,
  imports: [CommonModule, FontAwesomeModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  template: `
    <div
      class="ui-split-button"
      [class]="'ui-split-button--' + size + ' ui-split-button--' + variant + (disabled ? ' ui-split-button--disabled' : '') + (loading ? ' ui-split-button--loading' : '') + (fullWidth ? ' ui-split-button--full-width' : '')">
      
      <!-- Primary button -->
      <button
        class="ui-split-button__primary"
        [disabled]="disabled || loading"
        [type]="type"
        (click)="handlePrimaryClick($event)">
        
        @if (loading) {
          <div class="ui-split-button__loader">
            <div class="ui-split-button__spinner"></div>
          </div>
        } @else {
          <div class="ui-split-button__content">
            @if (icon && iconPosition === 'left') {
              <fa-icon [icon]="icon" class="ui-split-button__icon ui-split-button__icon--left"></fa-icon>
            }
            <span class="ui-split-button__text">
              <ng-content></ng-content>
            </span>
            @if (icon && iconPosition === 'right') {
              <fa-icon [icon]="icon" class="ui-split-button__icon ui-split-button__icon--right"></fa-icon>
            }
          </div>
        }
      </button>

      <!-- Dropdown button -->
      <button
        class="ui-split-button__dropdown"
        [disabled]="disabled || loading"
        type="button"
        [attr.aria-expanded]="isMenuOpen"
        [attr.aria-haspopup]="'menu'"
        (click)="handleDropdownClick($event)">
        
        <fa-icon 
          [icon]="faChevronDown" 
          class="ui-split-button__arrow">
        </fa-icon>
      </button>

      <!-- Dropdown menu -->
      @if (menuItems && menuItems.length > 0) {
        <div
          class="ui-split-button__menu"
          [class.ui-split-button__menu--open]="isMenuOpen"
          role="menu"
          [attr.aria-hidden]="!isMenuOpen">
          
          @for (item of menuItems; track item.label) {
            <button
              class="ui-split-button__menu-item"
              role="menuitem"
              [disabled]="item.disabled"
              (click)="handleMenuItemClick($event, item)">
              
              @if (item.icon) {
                <fa-icon 
                  [icon]="item.icon" 
                  class="ui-split-button__icon ui-split-button__icon--left">
                </fa-icon>
              }
              {{ item.label }}
            </button>
          }
        </div>
      }
    </div>
  `,
  styleUrl: './split-button.component.scss'
})
export class SplitButtonComponent {
  @Input() variant: SplitButtonVariant = 'filled';
  @Input() size: SplitButtonSize = '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: SplitButtonIconPosition = 'left';
  @Input() menuItems: SplitButtonMenuItem[] = [];

  @Output() primaryClicked = new EventEmitter<Event>();
  @Output() menuItemClicked = new EventEmitter<{ event: Event; item: SplitButtonMenuItem }>();
  @Output() dropdownToggled = new EventEmitter<boolean>();

  isMenuOpen = false;
  faChevronDown = faChevronDown;

  @HostListener('document:click', ['$event'])
  onDocumentClick(event: Event): void {
    const target = event.target as Element;
    const splitButton = target.closest('.ui-split-button');
    
    if (!splitButton || !splitButton.contains(target)) {
      this.closeMenu();
    }
  }

  @HostListener('document:keydown', ['$event'])
  onDocumentKeydown(event: KeyboardEvent): void {
    if (event.key === 'Escape' && this.isMenuOpen) {
      this.closeMenu();
    }
  }

  handlePrimaryClick(event: Event): void {
    if (!this.disabled && !this.loading) {
      this.primaryClicked.emit(event);
      this.closeMenu();
    }
  }

  handleDropdownClick(event: Event): void {
    if (!this.disabled && !this.loading) {
      event.stopPropagation();
      this.toggleMenu();
    }
  }

  handleMenuItemClick(event: Event, item: SplitButtonMenuItem): void {
    if (!item.disabled) {
      event.stopPropagation();
      this.menuItemClicked.emit({ event, item });
      this.closeMenu();
    }
  }

  private toggleMenu(): void {
    this.isMenuOpen = !this.isMenuOpen;
    this.dropdownToggled.emit(this.isMenuOpen);
  }

  private closeMenu(): void {
    if (this.isMenuOpen) {
      this.isMenuOpen = false;
      this.dropdownToggled.emit(false);
    }
  }
}