import { Component, OnInit } from '@angular/core';
import { NavController, AlertController, ToastController } from '@ionic/angular';
import { FamilyService } from '../services/family.service'; // 确认路径是否正确
import { FamilyMember} from '../services/family.service';
@Component({
  selector: 'app-manage-family',
  templateUrl: './manage-family.page.html',
  styleUrls: ['./manage-family.page.scss'],
})
export class ManageFamilyPage implements OnInit {
  familyMembers: any[] = [];
  isLoading = true; // 加载指示器
  error: string | null = null;

  constructor(
    private navCtrl: NavController,
    private familyService: FamilyService,
    private alertController: AlertController,
    private toastCtrl: ToastController
  ) {}

  ngOnInit() {
    this.loadFamilyMembers();
  }

  loadFamilyMembers() {
    this.isLoading = true;
    this.error = null;

    this.familyService.getFamilyMembers().subscribe(
      (members: any[]) => {
        this.familyMembers = members;
        this.isLoading = false;
      },
      (err) => {
        this.error = '无法加载家庭成员数据，请稍后再试。';
        this.showToast('无法加载家庭成员数据，请稍后再试。');
        this.isLoading = false;
      }
    );
  }

  async addFamilyMember() {
    const alert = await this.alertController.create({
      header: '添加家庭成员',
      inputs: [
        {
          name: 'name',
          type: 'text',
          placeholder: '姓名'
        },
        {
          name: 'relationship',
          type: 'text',
          placeholder: '关系'
        },
        {
          name: 'avatar',
          type: 'text',
          placeholder: '头像URL (可选)'
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '确认',
          handler: (data) => {
            if (data.name && data.relationship) {
              this.familyService.addFamilyMember(data).subscribe(
                (newMember) => {
                  this.showToast('家庭成员已成功添加。');
                  this.loadFamilyMembers();
                },
                (error) => {
                  this.showToast('添加家庭成员时发生错误，请稍后再试。');
                }
              );
            } else {
              this.showToast('请填写必填字段。');
            }
            return false; // 防止默认行为
          }
        }
      ]
    });
    await alert.present();
  }
  
  async editMember(member: FamilyMember) {
    const alert = await this.alertController.create({
      header: '编辑家庭成员',
      inputs: [
        {
          name: 'name',
          type: 'text',
          value: member.name,
          placeholder: '姓名'
        },
        {
          name: 'relationship',
          type: 'text',
          value: member.relationship,
          placeholder: '关系'
        },
        {
          name: 'avatar',
          type: 'text',
          value: member.avatar || '',
          placeholder: '头像URL (可选)'
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '确认',
          handler: (data) => {
            // Ensure that required fields are not undefined before updating
            if (data.name !== undefined && data.relationship !== undefined) {
              this.familyService.updateFamilyMember(member.id, data).subscribe(
                () => {
                  this.showToast('家庭成员信息已更新。');
                  this.loadFamilyMembers();
                },
                (error) => {
                  this.showToast('更新家庭成员时发生错误，请稍后再试。');
                }
              );
            } else {
              this.showToast('请填写必填字段。');
            }
            return false; // 防止默认行为
          }
        }
      ]
    });
    await alert.present();
  }

  async removeFamilyMember(memberId: string) {
    try {
      await this.familyService.removeFamilyMember(memberId).toPromise();
      this.showToast('家庭成员已成功移除。');
      this.loadFamilyMembers(); // 刷新列表
    } catch (error) {
      this.showToast('移除家庭成员时发生错误，请稍后再试。');
    }
  }

  backToPreviousPage() {
    this.navCtrl.back();
  }

  // Toast提示方法
  async showToast(message: string) {
    const toast = await this.toastCtrl.create({
      message,
      duration: 3000,
      position: 'bottom'
    });
    toast.present();
  }
}