import { Component, OnInit, ViewChild, ElementRef, AfterViewChecked } from '@angular/core';
import { trigger, transition, style, animate } from '@angular/animations';

interface ChatMessage {
  content: string;
  isAI: boolean;
  time: string;
  status?: 'sending' | 'sent' | 'error';
}

@Component({
  selector: 'app-page-aichat',
  templateUrl: './page-aichat.page.html',
  styleUrls: ['./page-aichat.page.scss'],
  standalone: false,
  animations: [
    trigger('messageAnim', [
      transition(':enter', [
        style({ opacity: 0, transform: 'translateY(20px)' }),
        animate('300ms cubic-bezier(0.4, 0, 0.2, 1)', 
          style({ opacity: 1, transform: 'translateY(0)' }))
      ])
    ])
  ]
})
export class PageAichatPage implements OnInit, AfterViewChecked {
  @ViewChild('messagesContainer') private messagesContainer!: ElementRef;
  @ViewChild('messageInput') messageInput!: ElementRef;

  messages: ChatMessage[] = [];
  newMessage = '';
  isInputFocused = false;

  get canSend(): boolean {
    return this.newMessage.trim().length > 0;
  }

  ngOnInit() {
    this.addAIMessage('您好！我是您的智能食谱助手，您可以输入食材名称，我会为您推荐相关食谱。例如："番茄"、"鸡肉"');
  }

  ngAfterViewChecked() {
    this.scrollToBottom();
  }

  async sendMessage() {
    if (!this.canSend) return;

    const userMessage = this.newMessage.trim();
    this.addUserMessage(userMessage);
    
    // 模拟发送过程
    await this.simulateSendDelay();
    
    // 添加AI回复
    this.addAIMessage(await this.generateAIReply(userMessage));
    
    this.newMessage = '';
    this.messageInput.nativeElement.focus();
  }

  private addUserMessage(content: string) {
    this.messages.push({
      content,
      isAI: false,
      time: this.getCurrentTime(),
      status: 'sending'
    });

    // 更新发送状态
    setTimeout(() => {
      const index = this.messages.length - 1;
      this.messages[index].status = Math.random() > 0.1 ? 'sent' : 'error';
    }, 1000);
  }

  private addAIMessage(content: string) {
    this.messages.push({
      content,
      isAI: true,
      time: this.getCurrentTime()
    });
  }

  private scrollToBottom() {
    try {
      setTimeout(() => {
        this.messagesContainer.nativeElement.scrollTop = 
          this.messagesContainer.nativeElement.scrollHeight;
      }, 100);
    } catch(err) { /* 处理滚动错误 */ }
  }

  private getCurrentTime(): string {
    return new Date().toLocaleTimeString([], { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  }

  private async simulateSendDelay(): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, 500));
  }

  private async generateAIReply(input: string): Promise<string> {
    // 模拟AI回复逻辑
    await new Promise(resolve => setTimeout(resolve, 800));
    return this.getRecipeRecommendations(input);
  }

  private getRecipeRecommendations(input: string): string {
    const recipes: { [key: string]: string[] } = {
      番茄: [
        "番茄炒蛋：将番茄切块，鸡蛋炒熟后加入番茄一起翻炒，调味即可。",
        "番茄汤：番茄去皮切块，加水煮开后调味，可加入鸡蛋液做成番茄蛋汤。",
        "番茄意大利面：番茄炒成酱，加入煮好的意大利面拌匀。"
      ],
      鸡肉: [
        "宫保鸡丁：鸡肉切丁，与花生米、青椒等一起炒制。",
        "香煎鸡胸肉：鸡胸肉用调料腌制后，放入锅中煎至两面金黄。",
        "鸡汤：鸡肉加水炖煮，加入姜片、葱段等调料。"
      ],
      土豆: [
        "土豆丝：土豆切成丝，清炒或酸辣口味都很不错。",
        "土豆炖牛肉：土豆与牛肉一起炖煮，口感软糯。",
        "薯条：土豆切成条，炸至金黄，可搭配番茄酱食用。"
      ]
    };

    for (const [ingredient, recipeList] of Object.entries(recipes)) {
      if (input.includes(ingredient)) {
        const randomIndex = Math.floor(Math.random() * recipeList.length);
        return `为您推荐使用 ${ingredient} 的食谱：${recipeList[randomIndex]}`;
      }
    }
    
    return `很抱歉，暂时没有找到与 "${input}" 相关的食谱。您可以尝试输入其他食材。`;
  }
}