import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy } from '@angular/core';
import { CommonModule } from '@angular/common';

export type ActionVariant = 'edit' | 'delete' | 'view' | 'download' | 'custom';
export type ActionSize = 'small' | 'medium' | 'large';

export interface TableAction {
  id: string;
  label: string;
  variant: ActionVariant;
  icon?: string;
  disabled?: boolean;
  hidden?: boolean;
  tooltip?: string;
  confirmMessage?: string;
}

@Component({
  selector: 'ui-table-actions',
  standalone: true,
  imports: [CommonModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div [class]="containerClasses">
      @for (action of visibleActions; track action.id) {
        <button
          [class]="getActionClasses(action)"
          [disabled]="action.disabled"
          [title]="action.tooltip || action.label"
          [attr.aria-label]="action.label"
          (click)="handleActionClick(action, $event)"
          type="button"
        >
          @if (action.icon) {
            <span class="ui-table-action__icon" [innerHTML]="action.icon"></span>
          }
          @if (showLabels) {
            <span class="ui-table-action__label">{{ action.label }}</span>
          }
        </button>
      }
      
      @if (hasMoreActions) {
        <div class="ui-table-actions__dropdown" [class.ui-table-actions__dropdown--open]="dropdownOpen">
          <button
            class="ui-table-action ui-table-action--more"
            [class]="getMoreButtonClasses()"
            (click)="toggleDropdown()"
            [attr.aria-expanded]="dropdownOpen"
            [attr.aria-haspopup]="true"
            type="button"
          >
            <span class="ui-table-action__icon">⋯</span>
            @if (showLabels) {
              <span class="ui-table-action__label">More</span>
            }
          </button>
          
          @if (dropdownOpen) {
            <div class="ui-table-actions__dropdown-menu" role="menu">
              @for (action of hiddenActions; track action.id) {
                <button
                  class="ui-table-actions__dropdown-item"
                  [disabled]="action.disabled"
                  [attr.aria-label]="action.label"
                  (click)="handleActionClick(action, $event)"
                  role="menuitem"
                  type="button"
                >
                  @if (action.icon) {
                    <span class="ui-table-action__icon" [innerHTML]="action.icon"></span>
                  }
                  <span class="ui-table-action__label">{{ action.label }}</span>
                </button>
              }
            </div>
          }
        </div>
      }
    </div>
  `,
  styleUrl: './table-actions.component.scss'
})
export class TableActionsComponent {
  @Input() actions: TableAction[] = [];
  @Input() size: ActionSize = 'medium';
  @Input() maxVisibleActions: number = 3;
  @Input() showLabels: boolean = false;
  @Input() compact: boolean = false;
  @Input() data: any = null; // Row data passed to action handlers
  @Input() index: number = -1; // Row index
  @Input() class: string = '';

  @Output() actionClick = new EventEmitter<{action: TableAction, data: any, index: number, event: Event}>();

  dropdownOpen = false;

  get visibleActions(): TableAction[] {
    const filtered = this.actions.filter(action => !action.hidden);
    return filtered.slice(0, this.maxVisibleActions);
  }

  get hiddenActions(): TableAction[] {
    const filtered = this.actions.filter(action => !action.hidden);
    return filtered.slice(this.maxVisibleActions);
  }

  get hasMoreActions(): boolean {
    return this.hiddenActions.length > 0;
  }

  get containerClasses(): string {
    return [
      'ui-table-actions',
      `ui-table-actions--${this.size}`,
      this.compact ? 'ui-table-actions--compact' : '',
      this.showLabels ? 'ui-table-actions--with-labels' : '',
      this.class
    ].filter(Boolean).join(' ');
  }

  getActionClasses(action: TableAction): string {
    return [
      'ui-table-action',
      `ui-table-action--${action.variant}`,
      action.disabled ? 'ui-table-action--disabled' : '',
    ].filter(Boolean).join(' ');
  }

  getMoreButtonClasses(): string {
    return [
      `ui-table-action--${this.size}`,
      this.dropdownOpen ? 'ui-table-action--active' : ''
    ].filter(Boolean).join(' ');
  }

  handleActionClick(action: TableAction, event: Event): void {
    if (action.disabled) {
      return;
    }

    // Close dropdown if it's open
    this.dropdownOpen = false;

    // Handle confirmation if required
    if (action.confirmMessage) {
      if (!confirm(action.confirmMessage)) {
        return;
      }
    }

    this.actionClick.emit({
      action,
      data: this.data,
      index: this.index,
      event
    });
  }

  toggleDropdown(): void {
    this.dropdownOpen = !this.dropdownOpen;
    
    if (this.dropdownOpen) {
      // Close dropdown when clicking outside
      setTimeout(() => {
        const handleClickOutside = (event: Event) => {
          const target = event.target as Element;
          if (!target.closest('.ui-table-actions__dropdown')) {
            this.dropdownOpen = false;
            document.removeEventListener('click', handleClickOutside);
          }
        };
        document.addEventListener('click', handleClickOutside);
      });
    }
  }
}