import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy, ViewEncapsulation } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { CommandSearchResult } from './command-palette.types';

@Component({
  selector: 'ui-command-palette-item',
  standalone: true,
  imports: [CommonModule, FontAwesomeModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  template: `
    <button
      type="button"
      class="ui-command-palette-item"
      [class.ui-command-palette-item--selected]="selected"
      [class.ui-command-palette-item--disabled]="result.command.disabled"
      [attr.aria-selected]="selected"
      [attr.aria-disabled]="result.command.disabled"
      role="option"
      (click)="handleClick()"
      (mouseenter)="handleMouseEnter()"
    >
      <div class="ui-command-palette-item__content">
        @if (result.command.icon) {
          <div class="ui-command-palette-item__icon" aria-hidden="true">
            <fa-icon [icon]="result.command.icon"></fa-icon>
          </div>
        }
        
        <div class="ui-command-palette-item__text">
          <div class="ui-command-palette-item__title">
            @if (result.highlightRanges.length > 0) {
              @for (segment of getHighlightedSegments(); track $index) {
                @if (segment.highlighted) {
                  <mark class="ui-command-palette-item__highlight">{{ segment.text }}</mark>
                } @else {
                  <span>{{ segment.text }}</span>
                }
              }
            } @else {
              {{ result.command.title }}
            }
          </div>
          
          @if (result.command.description) {
            <div class="ui-command-palette-item__description">
              {{ result.command.description }}
            </div>
          }
        </div>
        
        @if (result.command.shortcut && result.command.shortcut.length > 0) {
          <div class="ui-command-palette-item__shortcut" aria-hidden="true">
            @for (key of result.command.shortcut; track key; let last = $last) {
              <kbd class="ui-command-palette-item__kbd">{{ key }}</kbd>
              @if (!last) {
                <span class="ui-command-palette-item__plus">+</span>
              }
            }
          </div>
        }
      </div>
    </button>
  `,
  styleUrl: './command-palette-item.component.scss'
})
export class CommandPaletteItemComponent {
  @Input({ required: true }) result!: CommandSearchResult;
  @Input() selected = false;
  
  @Output() itemClick = new EventEmitter<CommandSearchResult>();
  @Output() itemHover = new EventEmitter<CommandSearchResult>();

  handleClick(): void {
    if (!this.result.command.disabled) {
      this.itemClick.emit(this.result);
    }
  }

  handleMouseEnter(): void {
    this.itemHover.emit(this.result);
  }

  getHighlightedSegments(): Array<{ text: string; highlighted: boolean }> {
    const title = this.result.command.title;
    const ranges = this.result.highlightRanges;
    
    if (ranges.length === 0) {
      return [{ text: title, highlighted: false }];
    }

    const segments: Array<{ text: string; highlighted: boolean }> = [];
    let currentIndex = 0;

    // Sort ranges by start position
    const sortedRanges = [...ranges].sort((a, b) => a.start - b.start);

    for (const range of sortedRanges) {
      // Add non-highlighted text before this range
      if (currentIndex < range.start) {
        segments.push({
          text: title.substring(currentIndex, range.start),
          highlighted: false
        });
      }

      // Add highlighted text
      segments.push({
        text: title.substring(range.start, range.end),
        highlighted: true
      });

      currentIndex = range.end;
    }

    // Add remaining non-highlighted text
    if (currentIndex < title.length) {
      segments.push({
        text: title.substring(currentIndex),
        highlighted: false
      });
    }

    return segments;
  }
}