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

export type BottomNavigationSize = 'sm' | 'md' | 'lg';
export type BottomNavigationVariant = 'default' | 'primary' | 'secondary';

export interface BottomNavigationItem {
  id: string;
  label: string;
  icon?: string;
  badge?: string | number;
  disabled?: boolean;
  href?: string;
  route?: string;
}

@Component({
  selector: 'ui-bottom-navigation',
  standalone: true,
  imports: [CommonModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  template: `
    <nav 
      class="ui-bottom-navigation"
      [class.ui-bottom-navigation--{{size}}]="size"
      [class.ui-bottom-navigation--{{variant}}]="variant"
      [class.ui-bottom-navigation--elevated]="elevated"
      [class.ui-bottom-navigation--hidden]="hidden"
      [attr.aria-label]="ariaLabel"
      role="navigation">
      
      @for (item of items; track item.id) {
        <a 
          class="ui-bottom-navigation__item"
          [class.ui-bottom-navigation__item--active]="activeItemId === item.id"
          [class.ui-bottom-navigation__item--disabled]="item.disabled"
          [class.ui-bottom-navigation__item--has-badge]="item.badge"
          [href]="item.href || null"
          [attr.aria-current]="activeItemId === item.id ? 'page' : null"
          [attr.aria-disabled]="item.disabled"
          [tabindex]="item.disabled ? -1 : 0"
          (click)="handleItemClick($event, item)"
          (keydown)="handleItemKeydown($event, item)">
          
          @if (item.icon) {
            <span class="ui-bottom-navigation__icon" aria-hidden="true">
              <ng-content [select]="'[data-icon=' + item.id + ']'"></ng-content>
            </span>
          }
          
          @if (item.label) {
            <span class="ui-bottom-navigation__label">{{ item.label }}</span>
          }
          
          @if (item.badge) {
            <span class="ui-bottom-navigation__badge" [attr.aria-label]="getBadgeAriaLabel(item.badge)">
              {{ getBadgeDisplay(item.badge) }}
            </span>
          }
        </a>
      }
    </nav>
  `,
  styleUrl: './bottom-navigation.component.scss'
})
export class BottomNavigationComponent {
  @Input() size: BottomNavigationSize = 'md';
  @Input() variant: BottomNavigationVariant = 'default';
  @Input() elevated = false;
  @Input() hidden = false;
  @Input() items: BottomNavigationItem[] = [];
  @Input() activeItemId?: string;
  @Input() ariaLabel = 'Bottom navigation';
  
  @Output() itemClicked = new EventEmitter<BottomNavigationItem>();
  @Output() activeItemChanged = new EventEmitter<string>();
  
  handleItemClick(event: MouseEvent, item: BottomNavigationItem): void {
    if (item.disabled) {
      event.preventDefault();
      return;
    }
    
    // If it's a route navigation, prevent default to let router handle it
    if (item.route && !item.href) {
      event.preventDefault();
    }
    
    // Update active item if not disabled
    if (this.activeItemId !== item.id) {
      this.activeItemChanged.emit(item.id);
    }
    
    // Emit item clicked event
    this.itemClicked.emit(item);
  }
  
  handleItemKeydown(event: KeyboardEvent, item: BottomNavigationItem): void {
    if (event.key === 'Enter' || event.key === ' ') {
      event.preventDefault();
      this.handleItemClick(event as any, item);
    } else if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
      event.preventDefault();
      this.navigateToAdjacentItem(event.key === 'ArrowLeft' ? -1 : 1);
    }
  }
  
  private navigateToAdjacentItem(direction: number): void {
    const enabledItems = this.items.filter(item => !item.disabled);
    const currentIndex = enabledItems.findIndex(item => item.id === this.activeItemId);
    
    if (currentIndex === -1) return;
    
    const nextIndex = (currentIndex + direction + enabledItems.length) % enabledItems.length;
    const nextItem = enabledItems[nextIndex];
    
    if (nextItem) {
      this.activeItemChanged.emit(nextItem.id);
      
      // Focus the next item
      setTimeout(() => {
        const itemElement = document.querySelector(
          `.ui-bottom-navigation__item[aria-current="page"]`
        ) as HTMLElement;
        itemElement?.focus();
      });
    }
  }
  
  getBadgeDisplay(badge: string | number): string {
    if (typeof badge === 'number' && badge > 99) {
      return '99+';
    }
    return badge.toString();
  }
  
  getBadgeAriaLabel(badge: string | number): string {
    if (typeof badge === 'number') {
      return badge > 99 ? 'More than 99 notifications' : `${badge} notifications`;
    }
    return `Badge: ${badge}`;
  }
}