import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AlertController } from '@ionic/angular/standalone';
import { 
  IonHeader, 
  IonToolbar, 
  IonTitle, 
  IonContent,
  IonList,
  IonItem,
  IonLabel,
  IonButton,
  IonIcon,
  IonFab,
  IonFabButton,
  IonButtons,
  IonBackButton
} from '@ionic/angular/standalone';
import { NgFor, NgIf } from '@angular/common';
import { addIcons } from 'ionicons';
import { add, create, trash } from 'ionicons/icons';
import { DatabaseService, CustomTeacher } from '../../services/database.service';

@Component({
  selector: 'app-custom-teacher',
  templateUrl: './custom-teacher.page.html',
  styleUrls: ['./custom-teacher.page.scss'],
  standalone: true,
  imports: [
    IonHeader,
    IonToolbar,
    IonTitle,
    IonContent,
    IonList,
    IonItem,
    IonLabel,
    IonButton,
    IonIcon,
    IonFab,
    IonFabButton,
    IonButtons,
    IonBackButton,
    NgFor,
    NgIf
  ]
})
export class CustomTeacherPage implements OnInit {
  customTeachers: CustomTeacher[] = [];
  userId: string = ''; // 这里需要从认证服务获取

  constructor(
    private dbService: DatabaseService,
    private router: Router,
    private alertController: AlertController
  ) {
    addIcons({ add, create, trash });
  }

  async ngOnInit() {
    // TODO: 从认证服务获取userId
    this.userId = 'testUser'; // 临时使用测试用户ID
    await this.loadCustomTeachers();
  }

  async loadCustomTeachers() {
    try {
      this.customTeachers = await this.dbService.getUserCustomTeachers(this.userId);
    } catch (error) {
      console.error('Error loading custom teachers:', error);
      // 显示错误提示
      const alert = await this.alertController.create({
        header: '错误',
        message: '加载自定义教师失败',
        buttons: ['确定']
      });
      await alert.present();
    }
  }

  async addTeacher() {
    // 导航到添加教师页面
    this.router.navigate(['/custom-teacher/add']);
  }

  async editTeacher(teacher: CustomTeacher) {
    // 导航到编辑教师页面
    this.router.navigate(['/custom-teacher/edit', teacher.objectId]);
  }

  async deleteTeacher(teacher: CustomTeacher) {
    const alert = await this.alertController.create({
      header: '确认删除',
      message: `确定要删除教师"${teacher.name}"吗？`,
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '删除',
          role: 'destructive',
          handler: async () => {
            try {
              await this.dbService.deleteCustomTeacher(teacher.objectId!);
              await this.loadCustomTeachers(); // 重新加载列表
            } catch (error) {
              console.error('Error deleting teacher:', error);
              const errorAlert = await this.alertController.create({
                header: '错误',
                message: '删除失败',
                buttons: ['确定']
              });
              await errorAlert.present();
            }
          }
        }
      ]
    });
    await alert.present();
  }
} 