import { Component, Input, computed, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { CustomerFeedback } from '../../../models/project.model';

export interface ReviewStats {
  totalCount: number;
  averageScore: number;
  satisfiedCount: number;
  unsatisfiedCount: number;
  pendingCount: number;
  processedCount: number;
  categoryStats: { [key: string]: number };
}

@Component({
  selector: 'app-customer-review-card',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './customer-review-card.html',
  styleUrls: ['./customer-review-card.scss']
})
export class CustomerReviewCardComponent {
  @Input() feedbacks: CustomerFeedback[] = [];
  
  // 筛选条件
  statusFilter = signal<string>('all');
  categoryFilter = signal<string>('all');
  scoreFilter = signal<string>('all');
  
  // 评价分类
  categories = [
    { value: 'color', label: '色彩问题' },
    { value: 'furniture', label: '家具款式问题' },
    { value: 'lighting', label: '光线问题' },
    { value: 'layout', label: '布局问题' },
    { value: 'material', label: '材质问题' },
    { value: 'other', label: '其他问题' }
  ];
  
  // 计算统计数据
  stats = computed<ReviewStats>(() => {
    const feedbacks = this.feedbacks || [];
    
    const categoryStats: { [key: string]: number } = {};
    this.categories.forEach(cat => {
      categoryStats[cat.value] = feedbacks.filter(f => this.getFeedbackCategory(f) === cat.value).length;
    });
    
    const scores = feedbacks.filter(f => f.rating !== undefined).map(f => f.rating || 0);
    const averageScore = scores.length > 0 ? scores.reduce((sum, score) => sum + score, 0) / scores.length : 0;
    
    return {
      totalCount: feedbacks.length,
      averageScore: Math.round(averageScore * 10) / 10,
      satisfiedCount: feedbacks.filter(f => f.isSatisfied).length,
      unsatisfiedCount: feedbacks.filter(f => !f.isSatisfied).length,
      pendingCount: feedbacks.filter(f => f.status === '待处理').length,
      processingCount: feedbacks.filter(f => f.status === '处理中').length,
      processedCount: feedbacks.filter(f => f.status === '已解决').length,
      categoryStats
    };
  });
  
  // 筛选后的评价列表
  filteredFeedbacks = computed(() => {
    let filtered = this.feedbacks || [];
    
    // 状态筛选
    const status = this.statusFilter();
    if (status !== 'all') {
      if (status === 'satisfied') {
        filtered = filtered.filter(f => f.isSatisfied);
      } else if (status === 'unsatisfied') {
        filtered = filtered.filter(f => !f.isSatisfied);
      } else {
        filtered = filtered.filter(f => f.status === status);
      }
    }
    
    // 分类筛选
    const category = this.categoryFilter();
    if (category !== 'all') {
      filtered = filtered.filter(f => this.getFeedbackCategory(f) === category);
    }
    
    // 评分筛选
    const score = this.scoreFilter();
    if (score !== 'all') {
      if (score === 'high') {
        filtered = filtered.filter(f => (f.rating || 0) >= 4);
      } else if (score === 'medium') {
        filtered = filtered.filter(f => (f.rating || 0) >= 2 && (f.rating || 0) < 4);
      } else if (score === 'low') {
        filtered = filtered.filter(f => (f.rating || 0) < 2);
      }
    }
    
    return filtered.sort((a, b) => {
      // 按状态排序：待处理 > 已处理，按时间倒序
      if (a.status !== b.status) {
        if (a.status === '待处理') return -1;
        if (b.status === '待处理') return 1;
      }
      return new Date(b.updatedAt || b.createdAt).getTime() - new Date(a.updatedAt || a.createdAt).getTime();
    });
  });
  
  // 获取反馈分类
  getFeedbackCategory(feedback: CustomerFeedback): string {
    const content = feedback.content.toLowerCase();
    const location = (feedback.problemLocation || '').toLowerCase();
    
    if (content.includes('色彩') || content.includes('颜色') || location.includes('色彩')) {
      return 'color';
    } else if (content.includes('家具') || content.includes('沙发') || content.includes('桌子') || location.includes('家具')) {
      return 'furniture';
    } else if (content.includes('光线') || content.includes('照明') || content.includes('灯光')) {
      return 'lighting';
    } else if (content.includes('布局') || content.includes('空间') || content.includes('摆放')) {
      return 'layout';
    } else if (content.includes('材质') || content.includes('质感') || content.includes('纹理')) {
      return 'material';
    }
    return 'other';
  }
  
  // 获取分类标签
  getCategoryLabel(category: string): string {
    const cat = this.categories.find(c => c.value === category);
    return cat ? cat.label : '其他问题';
  }
  
  // 获取评分星级
  getStarRating(score: number): string[] {
    const stars = [];
    for (let i = 1; i <= 5; i++) {
      if (i <= score) {
        stars.push('★');
      } else if (i - 0.5 <= score) {
        stars.push('☆');
      } else {
        stars.push('☆');
      }
    }
    return stars;
  }
  
  // 获取状态样式类
  getStatusClass(feedback: CustomerFeedback): string {
    if (feedback.status === '已解决') return 'processed';
    if (feedback.status === '处理中') return 'processing';
    return 'pending';
  }
  
  // 获取评分样式类
  getScoreClass(score: number): string {
    if (score >= 4) return 'high';
    if (score >= 2) return 'medium';
    return 'low';
  }
  
  // 更新筛选条件
  updateStatusFilter(status: string): void {
    this.statusFilter.set(status);
  }

  updateCategoryFilter(event: any): void {
    this.categoryFilter.set(event.target.value);
  }

  updateScoreFilter(event: any): void {
    this.scoreFilter.set(event.target.value);
  }
}