import { Component, Input } from '@angular/core';
import { AlertController, IonGrid, IonIcon, ModalController } from '@ionic/angular/standalone';
import { IonRow, IonCol, IonHeader, IonToolbar, IonTitle, IonButtons, IonButton, IonContent, IonCard, IonCardHeader, IonCardTitle, IonCardContent, IonItem, IonLabel, IonInput, IonToggle } from '@ionic/angular/standalone';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { addIcons } from 'ionicons';
import { closeCircleOutline, createOutline, checkmarkCircleOutline } from 'ionicons/icons';
@Component({
  selector: 'app-edit-plan-modal',
  templateUrl: './edit-plan-modal.component.html',
  styleUrls: ['./edit-plan-modal.component.scss'],
  standalone: true,
  imports: [
    IonIcon,
    IonGrid,
    IonRow,
    IonCol,
    IonHeader,
    IonToolbar,
    IonTitle,
    IonButtons,
    IonButton,
    IonContent,
    IonCard,
    IonCardHeader,
    IonCardTitle,
    IonCardContent,
    IonItem,
    IonLabel,
    IonInput,
    IonToggle,
    FormsModule,
    CommonModule
  ]
})
export class EditPlanModalComponent {
  @Input() plan: any;  // 接收传入的计划数据
  constructor(private modalCtrl: ModalController, private alertController: AlertController) {
    addIcons({ closeCircleOutline, checkmarkCircleOutline, createOutline });
  }
  // 更新数据字段
  onChange(field: string, event: any) {
    const value = event.target.value;
    console.log('Before update:', this.plan.data);
    this.plan.set({ [field]: value });  // 使用 set 来更新数据
  }
  // 处理任务项的变化
  onTaskChange(index: number, field: string, event: any) {
    const value = event.target.value;
    this.plan.data.trainingItems[index][field] = value;
    const updatedTrainingItems = this.plan.data.trainingItems;
    this.plan.set({ "trainingItems": updatedTrainingItems });
  }
  // 保存修改并更新数据库
  async saveChanges() {
    try {
      await this.plan.save();
      console.log('计划修改成功');
      this.modalCtrl.dismiss(this.plan);
    } catch (error) {
      console.error('保存失败:', error);
    }
  }
  async deletePlan(day: any) {
    const alert = await this.alertController.create({
      header: '确认删除',
      message: '确定要删除此计划吗？',
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            console.log('删除操作被取消');
          }
        },
        {
          text: '确认',
          handler: () => {
            day.destroy()
              .then(() => {
                console.log('计划已删除');

                this.dismiss();
              })
              .catch((error: any) => {
                console.error('删除失败:', error);
              });
          }
        }
      ]
    });

    await alert.present();
  }
  dismiss() {
    this.modalCtrl.dismiss();
  }
}
