import { Component } from '@angular/core';
import { IonHeader, IonToolbar, IonTitle, IonContent, IonList, IonItem, IonLabel, IonIcon, IonButton, IonInput, IonFooter, IonButtons } from '@ionic/angular/standalone';
import { OnInit } from '@angular/core';

@Component({
  selector: 'app-fitness-coach',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss'],
  standalone: false,
  
})
// 在Tab3Page类中添加messages属性
export class Tab3Page implements OnInit {
  messages: Array<{content: string, isUser: boolean, time: string}> = [
    { 
      content: '欢迎使用AI私教服务', 
      isUser: false,
      time: new Date().toLocaleTimeString()
    }
  ];
  pastSessions: any[] = [];
  currentSession: any = null;
  newMessage = '';

  constructor() {
    this.loadSessions();
  }

  // 加载历史会话
  private loadSessions() {
    const saved = localStorage.getItem('fitnessSessions');
    if (saved) {
      this.pastSessions = JSON.parse(saved);
    }
  }

  // 保存会话到本地存储
  private saveSessions() {
    localStorage.setItem('fitnessSessions', JSON.stringify(this.pastSessions));
  }

  // 开始新会话
  startNewSession(type: string) {
    const session = {
      id: this.generateId(),
      type,
      messages: [{
        id: this.generateId(),
        sender: 'coach',
        content: this.getWelcomeMessage(type),
        timestamp: new Date()
      }],
      createdAt: new Date(),
      lastActive: new Date()
    };
    
    this.currentSession = session;
    
    // 添加到历史会话（不重复添加已存在的会话）
    if (!this.pastSessions.some(s => s.id === session.id)) {
      this.pastSessions.unshift(session);
      this.saveSessions();
    }
  }

  // 恢复会话
  restoreSession(sessionId: string) {
    const session = this.pastSessions.find(s => s.id === sessionId);
    if (session) {
      session.lastActive = new Date();
      this.currentSession = session;
      this.saveSessions();
    }
  }

  // 结束当前会话
  endSession() {
    this.currentSession = null;
  }

  // 发送消息
  sendMessage() {
    if (this.newMessage.trim() && this.currentSession) {
      // 添加用户消息
      this.currentSession.messages.push({
        id: this.generateId(),
        sender: 'user',
        content: this.newMessage,
        timestamp: new Date()
      });
      
      this.newMessage = '';
      this.currentSession.lastActive = new Date();
      this.saveSessions();
      
      // 模拟AI回复
      setTimeout(() => {
        this.generateCoachResponse();
      }, 1000);
    }
  }

  // 生成AI回复
  private generateCoachResponse() {
    if (!this.currentSession) return;
    
    let response = "我理解您的需求了。让我们继续讨论您的健身计划。";
    
    // 根据会话类型生成不同回复
    switch(this.currentSession.type) {
      case 'strength':
        response = "关于力量训练，我建议从基础动作如深蹲、卧推和硬拉开始，每周训练3次，每次45-60分钟。";
        break;
      case 'cardio':
        response = "有氧运动方面，建议从每周3次、每次30分钟的中等强度有氧开始，如快走或骑行。";
        break;
      case 'nutrition':
        response = "根据一般建议，每天摄入蛋白质约1.6克/公斤体重，碳水化合物3-5克/公斤体重，脂肪0.5-1克/公斤体重。";
        break;
    }
    
    this.currentSession.messages.push({
      id: this.generateId(),
      sender: 'coach',
      content: response,
      timestamp: new Date()
    });
    
    this.currentSession.lastActive = new Date();
    this.saveSessions();
  }

  // 生成随机ID
  private generateId(): string {
    return Math.random().toString(36).substring(2, 9);
  }

  // 获取会话图标
  getSessionIcon(type: string): string {
    const icons: Record<string, string> = {
      strength: 'barbell',
      cardio: 'walk',
      nutrition: 'nutrition',
      default: 'chatbubbles'
    };
return icons[type] || icons["default"];
  }

  // 获取会话标题
  getSessionTitle(type: string): string {
    const titles: Record<string, string> = {
      strength: '力量训练指导',
      cardio: '有氧运动指导',
      nutrition: '营养饮食建议',
      default: '健身咨询'
    };
    return titles[type] || titles["default"];
  }

  // 获取欢迎消息
  private getWelcomeMessage(type: string): string {
    const messages: Record<string, string> = {
      strength: '您好!我是力量训练教练Alex。您想重点训练哪个肌群?',
      cardio: '您好!我是有氧运动教练Sarah。您更喜欢哪种有氧运动方式?',
      nutrition: '您好!我是营养师Lisa。请告诉我您的健身目标和目前的饮食习惯。',
      default: '您好!我是您的AI健身教练。我如何能帮助您?'
    };
return messages[type] || messages["default"];
  }

  ngOnInit() {
    console.log('Tab3 initialized'); // 添加初始化日志
  }
}
