import { Component, Input, Output, EventEmitter, signal, computed, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { CommonModule } from '@angular/common';

// 定义流程阶段接口
export interface ProcessStage {
  id: string;
  title: string;
  status: 'pending' | 'in-progress' | 'completed';
  icon?: string;
  description?: string;
  clickable?: boolean;
}

@Component({
  selector: 'app-process-progress-bar',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div class="process-progress-bar">
      <!-- 进度概览 -->
      <div class="progress-overview">
        <div class="progress-info">
          <span class="progress-label">整体进度</span>
          <span class="progress-percentage">{{ completionPercentage() }}%</span>
        </div>
        <div class="progress-bar-overview">
          <div class="progress-fill" [style.width.%]="completionPercentage()"></div>
        </div>
      </div>
      
      <!-- 横向串联式流程状态显示条 -->
      <div class="progress-stages-container">
        @for (stage of stages; track stage.id; let i = $index) {
          <div class="stage-wrapper">
            <!-- 阶段节点 -->
            <div class="stage-node" 
                 [class.pending]="stage.status === 'pending'"
                 [class.in-progress]="stage.status === 'in-progress'"
                 [class.completed]="stage.status === 'completed'"
                 [class.clickable]="clickable()"
                 [attr.aria-label]="getAriaLabel(stage)"
                 [attr.tabindex]="clickable() ? 0 : -1"
                 (click)="onStageClick(stage)"
                 (keydown)="onStageKeydown($event, stage)"
                 (mouseenter)="onStageHover(stage, true)"
                 (mouseleave)="onStageHover(stage, false)">
              
              <!-- 状态图标 -->
              <div class="stage-icon">
                @if (stage.status === 'completed') {
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <path d="m9 12 2 2 4-4" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                } @else if (stage.status === 'in-progress') {
                  <div class="progress-dot"></div>
                } @else {
                  <div class="pending-dot"></div>
                }
              </div>
              
              <!-- 阶段内容 -->
              <div class="stage-content">
                <!-- 阶段标题 -->
                <div class="stage-title">{{ stage.title }}</div>
                
                <!-- 阶段描述 -->
                @if (stage.description) {
                  <div class="stage-description">{{ stage.description }}</div>
                }
                
                <!-- 状态指示器 -->
                <div class="stage-status-indicator" 
                     [class.status-pending]="stage.status === 'pending'"
                     [class.status-progress]="stage.status === 'in-progress'"
                     [class.status-completed]="stage.status === 'completed'">
                  {{ getStatusText(stage.status) }}
                </div>
              </div>
            </div>
            
            <!-- 连接线 -->
            @if (i < stages.length - 1) {
              <div class="stage-connector" 
                   [class.connector-completed]="isConnectorCompleted(i)">
                <div class="connector-line"></div>
                <div class="connector-arrow">
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <polyline points="9 18 15 12 9 6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                </div>
              </div>
            }
          </div>
        }
      </div>
    </div>
  `,
  styleUrls: ['./process-progress-bar.component.scss']
})
export class ProcessProgressBarComponent implements OnInit, OnChanges {
  @Input() stages: ProcessStage[] = [];
  @Input() clickable = signal<boolean>(true);
  
  @Output() stageClick = new EventEmitter<ProcessStage>();
  @Output() stageHover = new EventEmitter<{stage: ProcessStage, isHover: boolean}>();
  
  ngOnInit(): void {
    console.log('ProcessProgressBarComponent initialized');
    console.log('Initial stages:', this.stages);
    console.log('Initial stages length:', this.stages?.length || 0);
    
    if (!this.stages) {
      console.warn('Stages input is null or undefined');
      this.stages = [];
    }
  }
  
  ngOnChanges(changes: SimpleChanges): void {
    if (changes['stages']) {
      console.log('ProcessProgressBarComponent stages changed');
      console.log('New stages:', changes['stages'].currentValue);
      console.log('New stages length:', changes['stages'].currentValue?.length || 0);
      
      if (!changes['stages'].currentValue) {
        console.warn('New stages value is null or undefined');
        this.stages = [];
      }
    }
  }
  
  completionPercentage(): number {
    if (!this.stages || this.stages.length === 0) {
      console.log('No stages available for completion calculation');
      return 0;
    }
    
    const completedCount = this.stages.filter(stage => {
      if (!stage) {
        console.warn('Found null stage in completion calculation');
        return false;
      }
      return stage.status === 'completed';
    }).length;
    
    const percentage = Math.round((completedCount / this.stages.length) * 100);
    console.log(`Completion percentage: ${percentage}% (${completedCount}/${this.stages.length})`);
    return percentage;
  }
  
  onStageClick(stage: ProcessStage): void {
    if (this.clickable()) {
      this.stageClick.emit(stage);
    }
  }
  
  onStageKeydown(event: KeyboardEvent, stage: ProcessStage): void {
    if (event.key === 'Enter' || event.key === ' ') {
      event.preventDefault();
      this.onStageClick(stage);
    }
  }
  
  onStageHover(stage: ProcessStage, isHover: boolean): void {
    this.stageHover.emit({ stage, isHover });
  }
  
  isConnectorCompleted(index: number): boolean {
    const currentStage = this.stages[index];
    const nextStage = this.stages[index + 1];
    return currentStage.status === 'completed' && nextStage && nextStage.status !== 'pending';
  }
  
  getAriaLabel(stage: ProcessStage): string {
    return `${stage.title} - ${this.getStatusText(stage.status)}${stage.description ? ': ' + stage.description : ''}`;
  }
  
  getStatusText(status: string): string {
    switch (status) {
      case 'completed':
        return '已完成';
      case 'in-progress':
        return '进行中';
      case 'pending':
        return '未开始';
      default:
        return '未知';
    }
  }
}