import { Component, ChangeDetectorRef } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { ColorUsage } from '../../../../../lib/ncloud';
import { TestMessage, TestCompletion } from '../../../../../lib/completion';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

// 定义类型
interface TrendRecommendation {
  title: string;
  colors: string[];
  description: string;
}

interface PresetQuestion {
  text: string;
  description: string;
  icon: string;
}

@Component({
  selector: 'app-page-design',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './page-design.html',
  styleUrls: ['./page-design.scss']
})
export class PageDesignComponent {
  // 原有设计界面的变量（保持不变）
  activePart: string = 'hood';
  selectedColor: string = '#3498db';
  colors: string[] = [
    '#3498db', '#e74c3c', '#2ecc71', '#f1c40f', 
    '#9b59b6', '#1abc9c', '#e67e22', '#2c3e50', 
    '#ecf0f1', '#e84393', '#ffeaa7','#ffb6c1',
    '#98ff98','#b399d4','#ff7f50','#89cff0',
   '#ff9aa2','#40e0d0','#f0e68c','#c8a2c8'
  ];
  
  partColors: { [key: string]: string } = {
    'hood': '#3498db',
    'body': '#2980b9',
    'sleeve-left': '#3498db',
    'sleeve-right': '#3498db'
  };
  
  colorUsage: ColorUsage = new ColorUsage();

  // 新增的AI助手相关变量（完全保持不变）
  aiMessages: { text: string | SafeHtml; isUser: boolean; isLoading?: boolean; isTrend?: boolean }[] = [
    { text: '您好！我是您的羽绒服设计助手。我可以根据您的喜好推荐颜色搭配，或者帮您分析当前设计的流行度。有什么我可以帮您的吗？', isUser: false }
  ];
  aiInput: string = '';
  showAIModal: boolean = false;
  isAILoading: boolean = false;
  
  presetQuestions: PresetQuestion[] = [
    { 
      text: '推荐一些流行颜色搭配', 
      description: '获取当前最受欢迎的配色方案',
      icon: 'fas fa-palette'
    },
    { 
      text: '分析我的设计流行度', 
      description: '评估当前设计的市场吸引力',
      icon: 'fas fa-chart-line'
    },
    { 
      text: '生成3D预览效果', 
      description: '创建设计的3D可视化预览',
      icon: 'fas fa-cube'
    },
    { 
      text: '提供设计灵感', 
      description: '获取创意设计建议',
      icon: 'fas fa-lightbulb'
    }
  ];
  
  trendRecommendations: TrendRecommendation[] = [
    {
      title: '海洋蓝渐变',
      colors: ['#89CFF0', '#40E0D0', '#008080'],
      description: '从浅蓝到深蓝的渐变效果，清新自然'
    },
    {
      title: '日落橙黄',
      colors: ['#FF7F50', '#FFD700', '#FFA500'],
      description: '温暖活力的橙黄色系，充满活力'
    },
    {
      title: '森林绿系',
      colors: ['#98FF98', '#2E8B57', '#006400'],
      description: '自然森林色调，环保且时尚'
    }
  ];

  constructor(
    private cdr: ChangeDetectorRef,
    private sanitizer: DomSanitizer
  ) {}

  // 原有设计界面的方法（仅修改颜色处理部分）
  selectPart(part: string) {
    this.activePart = part;
  }

  selectColor(color: string) {
    this.selectedColor = color;
    this.partColors[this.activePart] = color;
    this.colorUsage.increment(color);
  }

  getPartGradient(part: string): string {
    const color = this.partColors[part];
    const darker = this.darkenColor(color, 20);
    return `linear-gradient(135deg, ${color}, ${darker})`;
  }

  resetDesign() {
    this.partColors = {
      'hood': '#3498db',
      'body': '#2980b9',
      'sleeve-left': '#3498db',
      'sleeve-right': '#3498db'
    };
    this.selectedColor = '#3498db';
    this.activePart = 'hood';
  }

  saveDesign() {
    alert('设计已保存！');
  }

  private darkenColor(color: string, percent: number): string {
    // 更健壮的颜色变暗算法
    const hex = color.replace('#', '');
    
    // 处理3位HEX格式
    const fullHex = hex.length === 3 
      ? hex.split('').map(c => c + c).join('')
      : hex.padEnd(6, '0').substring(0, 6);
    
    // 解析RGB分量
    const r = Math.max(0, Math.min(255, parseInt(fullHex.substring(0, 2), 16)));
    const g = Math.max(0, Math.min(255, parseInt(fullHex.substring(2, 4), 16)));
    const b = Math.max(0, Math.min(255, parseInt(fullHex.substring(4, 6), 16)));
    
    // 计算变暗值
    const amount = Math.round(2.55 * percent);
    const newR = Math.max(0, r - amount);
    const newG = Math.max(0, g - amount);
    const newB = Math.max(0, b - amount);
    
    // 转换回HEX
    const toHex = (c: number) => c.toString(16).padStart(2, '0');
    return `#${toHex(newR)}${toHex(newG)}${toHex(newB)}`;
  }

  getColorUsage(): { [key: string]: number } {
    return this.colorUsage.getAll();
  }

  // 新增的AI助手方法（完全保持不变）
  toggleAIModal() {
    this.showAIModal = !this.showAIModal;
    if (this.showAIModal) {
      this.showTrendRecommendations();
    }
  }
  
  showTrendRecommendations() {
    if (this.aiMessages.length > 1) return;
    
    let trendMessage = '根据当前流行趋势，我为您推荐以下设计方向：\n\n';
    
    this.trendRecommendations.forEach((trend: TrendRecommendation, index: number) => {
      trendMessage += `${index + 1}. ${trend.title}\n`;
      trendMessage += `   ${trend.description}\n`;
      trendMessage += `   推荐颜色: `;
      
      trend.colors.forEach((color: string) => {
        trendMessage += `<span class="color-dot" style="background-color:${color}"></span> `;
      });
      
      trendMessage += '\n\n';
    });
    
    trendMessage += '您可以直接选择应用这些推荐，或者告诉我您的具体需求！';
    
    this.aiMessages.push({ 
      text: this.sanitizer.bypassSecurityTrustHtml(trendMessage), 
      isUser: false,
      isTrend: true
    });
  }
  
  applyTrendRecommendation(index: number) {
    if (index < 0 || index >= this.trendRecommendations.length) return;
    
    const trend = this.trendRecommendations[index];
    
    // 应用推荐颜色
    this.partColors['hood'] = trend.colors[0];
    this.partColors['body'] = trend.colors[1];
    this.partColors['sleeve-left'] = trend.colors[0];
    this.partColors['sleeve-right'] = trend.colors[0];
    
    // 更新选中颜色
    this.selectedColor = trend.colors[0];
    
    this.aiMessages.push({ 
      text: `已应用推荐：${trend.title}`, 
      isUser: true 
    });
    
    setTimeout(() => {
      this.aiMessages.push({ 
        text: `太棒了！您已成功应用了${trend.title}设计。这个方案在当前非常流行，预计会受到年轻群体的喜爱。您想进一步调整还是保存设计？`, 
        isUser: false 
      });
    }, 500);
  }

  async sendAiMessage() {
    const text = this.aiInput.trim();
    if (!text) return;
    
    this.aiMessages.push({ text, isUser: true });
    this.aiInput = '';
    
    const aiReplyIndex = this.aiMessages.length;
    this.aiMessages.push({ text: '思考中...', isUser: false, isLoading: true });
    
    this.isAILoading = true;
    this.cdr.detectChanges();
    
    try {
      const messages: TestMessage[] = this.aiMessages
        .filter(msg => !msg.isLoading && typeof msg.text === 'string')
        .map(msg => ({
          role: msg.isUser ? 'user' : 'assistant',
          content: msg.text as string
        }));
      
      const completion = new TestCompletion(messages);
      
      await completion.sendMessage(null, (content) => {
        this.aiMessages[aiReplyIndex].text = content;
        this.cdr.detectChanges();
      });
      
    } catch (error) {
      console.error('AI请求失败:', error);
      this.aiMessages[aiReplyIndex].text = '抱歉，AI助手暂时无法回答，请稍后再试。';
    } finally {
      this.aiMessages[aiReplyIndex].isLoading = false;
      this.isAILoading = false;
      this.cdr.detectChanges();
    }
  }
  
  usePresetQuestion(question: string) {
    this.aiInput = question;
    this.sendAiMessage();
  }
}