import { Component, Inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import { MatInputModule } from '@angular/material/input';
import { MatIconModule } from '@angular/material/icon';
import { MatChipsModule } from '@angular/material/chips';

export interface ComparisonItemData {
  name: string;
  category: string;
  icon: string;
  iconClass: string;
  metrics: { [key: string]: string };
}

export interface DialogData {
  dimension: string;
  availableMetrics: string[];
}

@Component({
  selector: 'app-add-comparison-dialog',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    MatDialogModule,
    MatButtonModule,
    MatFormFieldModule,
    MatSelectModule,
    MatInputModule,
    MatIconModule,
    MatChipsModule
  ],
  template: `
    <h2 mat-dialog-title>
      <mat-icon>add_circle</mat-icon>
      添加对比项
    </h2>
    
    <mat-dialog-content>
      <div class="form-section">
        <mat-form-field appearance="outline" class="full-width">
          <mat-label>项目名称</mat-label>
          <input matInput [(ngModel)]="itemData.name" placeholder="请输入项目名称">
          <mat-icon matSuffix>edit</mat-icon>
        </mat-form-field>
      </div>

      <div class="form-section">
        <mat-form-field appearance="outline" class="full-width">
          <mat-label>项目类别</mat-label>
          <mat-select [(value)]="itemData.category">
            <mat-option value="研发部门">研发部门</mat-option>
            <mat-option value="创意部门">创意部门</mat-option>
            <mat-option value="策略部门">策略部门</mat-option>
            <mat-option value="执行部门">执行部门</mat-option>
            <mat-option value="支持部门">支持部门</mat-option>
            <mat-option value="管理部门">管理部门</mat-option>
          </mat-select>
        </mat-form-field>
      </div>

      <div class="form-section">
        <mat-form-field appearance="outline" class="full-width">
          <mat-label>图标</mat-label>
          <mat-select [(value)]="itemData.icon" (selectionChange)="updateIconClass()">
            <mat-option value="code">
              <mat-icon>code</mat-icon>
              代码 (技术)
            </mat-option>
            <mat-option value="palette">
              <mat-icon>palette</mat-icon>
              调色板 (设计)
            </mat-option>
            <mat-option value="lightbulb">
              <mat-icon>lightbulb</mat-icon>
              灯泡 (创意)
            </mat-option>
            <mat-option value="trending_up">
              <mat-icon>trending_up</mat-icon>
              趋势 (运营)
            </mat-option>
            <mat-option value="groups">
              <mat-icon>groups</mat-icon>
              团队 (人事)
            </mat-option>
            <mat-option value="analytics">
              <mat-icon>analytics</mat-icon>
              分析 (数据)
            </mat-option>
            <mat-option value="campaign">
              <mat-icon>campaign</mat-icon>
              营销 (市场)
            </mat-option>
            <mat-option value="support">
              <mat-icon>support</mat-icon>
              支持 (客服)
            </mat-option>
          </mat-select>
        </mat-form-field>
      </div>

      <h3>绩效指标设置</h3>
      <div class="metrics-grid">
        @for (metric of data.availableMetrics; track metric) {
          <mat-form-field appearance="outline">
            <mat-label>{{ getMetricDisplayName(metric) }}</mat-label>
            <input 
              matInput 
              [(ngModel)]="itemData.metrics[metric]" 
              placeholder="0-100%"
              pattern="[0-9]+%?"
              (blur)="formatMetricValue(metric)">
            <span matSuffix>%</span>
          </mat-form-field>
        }
      </div>

      <div class="preview-section">
        <h3>预览</h3>
        <div class="item-preview">
          <div class="preview-header">
            <mat-icon [class]="itemData.iconClass">{{ itemData.icon }}</mat-icon>
            <div class="preview-info">
              <h4>{{ itemData.name || '新项目' }}</h4>
              <span class="preview-category">{{ itemData.category || '未分类' }}</span>
            </div>
          </div>
          <div class="preview-metrics">
            @for (metric of data.availableMetrics; track metric) {
              <div class="metric-preview">
                <span class="metric-name">{{ getMetricDisplayName(metric) }}</span>
                <span class="metric-value">{{ itemData.metrics[metric] || '0%' }}</span>
              </div>
            }
          </div>
        </div>
      </div>
    </mat-dialog-content>
    
    <mat-dialog-actions align="end">
      <button mat-button (click)="onCancel()">取消</button>
      <button mat-raised-button color="primary" (click)="onConfirm()" [disabled]="!isValid()">
        <mat-icon>add</mat-icon>
        添加
      </button>
    </mat-dialog-actions>
  `,
  styleUrls: ['../../../shared/styles/_hr-dialog.scss']
})
export class AddComparisonDialogComponent {
  itemData: ComparisonItemData = {
    name: '',
    category: '',
    icon: 'add_circle',
    iconClass: 'new-icon',
    metrics: {}
  };

  constructor(
    public dialogRef: MatDialogRef<AddComparisonDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData
  ) {
    // 初始化指标数据
    this.data.availableMetrics.forEach(metric => {
      this.itemData.metrics[metric] = '0%';
    });
  }

  getMetricDisplayName(metric: string): string {
    const metricNames: { [key: string]: string } = {
      'completion': '完成率',
      'quality': '质量评分',
      'efficiency': '效率指数',
      'satisfaction': '满意度',
      'innovation': '创新度'
    };
    return metricNames[metric] || metric;
  }

  updateIconClass(): void {
    const iconClassMap: { [key: string]: string } = {
      'code': 'tech-icon',
      'palette': 'design-icon',
      'lightbulb': 'product-icon',
      'trending_up': 'operation-icon',
      'groups': 'hr-icon',
      'analytics': 'data-icon',
      'campaign': 'marketing-icon',
      'support': 'support-icon'
    };
    this.itemData.iconClass = iconClassMap[this.itemData.icon] || 'new-icon';
  }

  formatMetricValue(metric: string): void {
    let value = this.itemData.metrics[metric];
    if (value && !value.endsWith('%')) {
      // 移除非数字字符，只保留数字
      const numericValue = value.replace(/[^\d]/g, '');
      if (numericValue) {
        // 确保值在0-100范围内
        const num = Math.min(100, Math.max(0, parseInt(numericValue)));
        this.itemData.metrics[metric] = num + '%';
      } else {
        this.itemData.metrics[metric] = '0%';
      }
    }
  }

  isValid(): boolean {
    return !!(this.itemData.name && this.itemData.category && this.itemData.icon);
  }

  onCancel(): void {
    this.dialogRef.close();
  }

  onConfirm(): void {
    if (this.isValid()) {
      this.dialogRef.close(this.itemData);
    }
  }
}