import { Component, Input, OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { IonicModule } from '@ionic/angular';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-edit-profile',
  templateUrl: 'edit-profile.component.html',
  styleUrls: ['edit-profile.component.scss'],
  imports: [IonicModule, CommonModule, FormsModule],
  standalone: true
})
export class EditProfileComponent implements OnInit {
  @Input() currentUser: any;

  name: string | undefined;
  gender: string | undefined;
  age: number | undefined;
  location: string | undefined;

  constructor(private modalCtrl: ModalController) {}

  ngOnInit() {
    // 尝试从缓存中获取数据
    const cachedData = localStorage.getItem('userProfile');
    if (cachedData) {
      const { name, gender, age, location } = JSON.parse(cachedData);
      this.name = name;
      this.gender = gender;
      this.age = age;
      this.location = location;
    } else if (this.currentUser) {
      this.name = this.currentUser.data.name || '';
      this.gender = this.currentUser.data.gender || '';
      this.age = this.currentUser.data.age || 0;
      this.location = this.currentUser.data.location || '';
    }
  }

  saveProfile() {
    const updatedData = {
      name: this.name,
      gender: this.gender,
      age: this.age,
      location: this.location
    };
    // 设置缓存
    localStorage.setItem('userProfile', JSON.stringify(updatedData));
    this.modalCtrl.dismiss(updatedData);
  }

  cancel() {
    this.modalCtrl.dismiss();
  }
}