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

type ListDetailSize = 'sm' | 'md' | 'lg';
type ListDetailVariant = 'default' | 'bordered' | 'elevated';
type MobileView = 'list' | 'detail';

export interface ListDetailNavigationEvent {
  view: MobileView;
  hasSelection: boolean;
}

@Component({
  selector: 'ui-list-detail-layout',
  standalone: true,
  imports: [CommonModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  template: `
    <div 
      class="ui-list-detail-layout"
      [class.ui-list-detail-layout--sm]="size === 'sm'"
      [class.ui-list-detail-layout--lg]="size === 'lg'"
      [class.ui-list-detail-layout--bordered]="variant === 'bordered'"
      [class.ui-list-detail-layout--elevated]="variant === 'elevated'"
      [class.ui-list-detail-layout--loading]="loading"
      [attr.role]="role"
      [attr.aria-label]="ariaLabel">
      
      <!-- Mobile Navigation Header -->
      <div class="ui-list-detail-layout__mobile-nav" *ngIf="showMobileNavigation">
        <button
          type="button"
          class="ui-list-detail-layout__mobile-nav-button"
          [disabled]="!hasSelection()"
          (click)="handleMobileNavigation('list')"
          [attr.aria-label]="backToListLabel">
          ← {{ backToListText }}
        </button>
        
        <span class="ui-list-detail-layout__mobile-nav-title">
          {{ currentView() === 'list' ? listTitle : detailTitle }}
        </span>
        
        <button
          type="button"
          class="ui-list-detail-layout__mobile-nav-button"
          [disabled]="!hasSelection()"
          (click)="handleMobileNavigation('detail')"
          [attr.aria-label]="viewDetailLabel">
          {{ viewDetailText }} →
        </button>
      </div>
      
      <!-- List Panel -->
      <div 
        class="ui-list-detail-layout__list"
        [class.ui-list-detail-layout__list--hidden-mobile]="currentView() === 'detail'"
        [attr.aria-label]="listAriaLabel"
        role="region">
        
        <div 
          class="ui-list-detail-layout__resize-handle"
          [attr.tabindex]="resizable ? 0 : -1"
          [attr.aria-label]="resizeHandleLabel"
          role="separator"
          aria-orientation="vertical"
          (keydown)="handleResizeKeydown($event)">
        </div>
        
        <ng-content select="[slot='list']"></ng-content>
      </div>
      
      <!-- Detail Panel -->
      <div 
        class="ui-list-detail-layout__detail"
        [class.ui-list-detail-layout__detail--hidden-mobile]="currentView() === 'list'"
        [class.ui-list-detail-layout__detail--empty]="!hasSelection() && showEmptyState"
        [attr.aria-label]="detailAriaLabel"
        role="region">
        
        @if (!hasSelection() && showEmptyState) {
          <div class="ui-list-detail-layout__empty-state">
            <ng-content select="[slot='empty']">
              {{ emptyStateText }}
            </ng-content>
          </div>
        } @else {
          <ng-content select="[slot='detail']"></ng-content>
        }
      </div>
    </div>
  `,
  styleUrl: './list-detail-layout.component.scss'
})
export class ListDetailLayoutComponent {
  // Appearance
  @Input() size: ListDetailSize = 'md';
  @Input() variant: ListDetailVariant = 'default';
  @Input() loading = false;
  
  // Functionality
  @Input() resizable = true;
  @Input() showEmptyState = true;
  @Input() showMobileNavigation = true;
  
  // Selection state
  @Input() 
  set selectedItem(value: any) {
    this._selectedItem.set(value);
  }
  get selectedItem() {
    return this._selectedItem();
  }
  private _selectedItem = signal<any>(null);
  
  // Mobile view state
  @Input()
  set mobileView(value: MobileView) {
    this._currentView.set(value);
  }
  get mobileView() {
    return this._currentView();
  }
  private _currentView = signal<MobileView>('list');
  
  // Text customization
  @Input() listTitle = 'List';
  @Input() detailTitle = 'Details';
  @Input() backToListText = 'Back to List';
  @Input() viewDetailText = 'View Details';
  @Input() emptyStateText = 'Select an item to view details';
  
  // Accessibility
  @Input() role = 'application';
  @Input() ariaLabel = 'List and detail view';
  @Input() listAriaLabel = 'Item list';
  @Input() detailAriaLabel = 'Item details';
  @Input() backToListLabel = 'Return to item list';
  @Input() viewDetailLabel = 'View item details';
  @Input() resizeHandleLabel = 'Resize panels';
  
  // Events
  @Output() selectionChanged = new EventEmitter<any>();
  @Output() mobileNavigated = new EventEmitter<ListDetailNavigationEvent>();
  @Output() panelResized = new EventEmitter<{ listWidth: number }>();
  
  // Computed properties
  currentView = this._currentView.asReadonly();
  
  hasSelection(): boolean {
    return this._selectedItem() != null;
  }
  
  // Event handlers
  handleMobileNavigation(view: MobileView): void {
    if (view === 'detail' && !this.hasSelection()) {
      return; // Can't navigate to detail without selection
    }
    
    this._currentView.set(view);
    this.mobileNavigated.emit({
      view,
      hasSelection: this.hasSelection()
    });
  }
  
  handleResizeKeydown(event: KeyboardEvent): void {
    if (!this.resizable) return;
    
    // Keyboard control for resize handle
    const step = 20; // pixels
    let deltaX = 0;
    
    switch (event.key) {
      case 'ArrowLeft':
        deltaX = -step;
        break;
      case 'ArrowRight':
        deltaX = step;
        break;
      case 'Home':
        // Reset to default size
        this.panelResized.emit({ listWidth: 320 });
        event.preventDefault();
        return;
      case 'End':
        // Maximize list panel
        this.panelResized.emit({ listWidth: 600 });
        event.preventDefault();
        return;
      default:
        return;
    }
    
    if (deltaX !== 0) {
      event.preventDefault();
      // In a real implementation, you'd calculate the new width
      // For demo purposes, we'll just emit the event
      this.panelResized.emit({ listWidth: 320 + deltaX });
    }
  }
  
  // Public methods for external control
  selectItem(item: any): void {
    this._selectedItem.set(item);
    this.selectionChanged.emit(item);
    
    // Auto-navigate to detail on mobile when item is selected
    if (window.innerWidth < 768) { // md breakpoint
      this._currentView.set('detail');
      this.mobileNavigated.emit({
        view: 'detail',
        hasSelection: true
      });
    }
  }
  
  clearSelection(): void {
    this._selectedItem.set(null);
    this.selectionChanged.emit(null);
    
    // Auto-navigate to list on mobile when selection is cleared
    if (window.innerWidth < 768) { // md breakpoint
      this._currentView.set('list');
      this.mobileNavigated.emit({
        view: 'list',
        hasSelection: false
      });
    }
  }
  
  showList(): void {
    this._currentView.set('list');
  }
  
  showDetail(): void {
    if (this.hasSelection()) {
      this._currentView.set('detail');
    }
  }
}