import { Component, OnInit } from '@angular/core';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { FmodeChatCompletion, MarkdownPreviewModule } from 'fmode-ng';

@Component({
  selector: 'app-page-training-plan',
  templateUrl: './page-training-plan.component.html',
  styleUrls: ['./page-training-plan.component.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule, CommonModule, MarkdownPreviewModule]
})
export class PageTrainingPlanComponent implements OnInit {
  // 用户输入
  userGoal: string = '';
  fitnessLevel: string = 'beginner';
  availableDays: number = 3;
  availableTime: number = 30;

  // AI响应
  aiContent: string = '请填写您的训练目标，然后点击"生成计划"按钮';
  isLoading: boolean = false;
  isPlanGenerated: boolean = false;

  // 训练水平选项
  fitnessLevels = [
    { value: 'beginner', label: '初级' },
    { value: 'intermediate', label: '中级' },
    { value: 'advanced', label: '高级' }
  ];

  constructor() { }

  ngOnInit() { }

  generatePlan() {
    if (!this.userGoal.trim()) {
      this.aiContent = '请输入您的训练目标';
      return;
    }

    this.isLoading = true;
    this.aiContent = '正在为您生成个性化训练计划...';
    this.isPlanGenerated = false;

    const now = new Date();
    const timeParams = `当前时间：${now.toLocaleString()}`;

    const prompt = `你是一名专业的健身教练，请根据以下信息为用户制定个性化的训练计划：
    
    用户目标: ${this.userGoal}
    健身水平: ${this.fitnessLevel}
    每周可训练天数: ${this.availableDays}天
    每次训练时间: ${this.availableTime}分钟
    
    请生成一个详细、科学的训练计划，包括:
    1. 训练目标概述
    2. 每周训练安排
    3. 每次训练的具体内容(动作名称、组数、次数、休息时间)
    4. 注意事项和建议
    
    使用清晰易读的格式，适当使用标题和分段。`;

    const completion = new FmodeChatCompletion([
      { role: "system", content: timeParams },
      { role: "user", content: prompt }
    ]);

    completion.sendCompletion().subscribe({
      next: (message: any) => {
        this.aiContent = message.content;
        if (message.complete) {
          this.isLoading = false;
          this.isPlanGenerated = true;
        }
      },
      error: (err) => {
        this.aiContent = '生成计划时出错，请重试';
        this.isLoading = false;
        console.error(err);
      }
    });
  }

  resetForm() {
    this.userGoal = '';
    this.fitnessLevel = 'beginner';
    this.availableDays = 3;
    this.availableTime = 30;
    this.aiContent = '请填写您的训练目标，然后点击"生成计划"按钮';
    this.isPlanGenerated = false;
  }

}
