import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NavController, Platform } from '@ionic/angular';
import { UserService } from '../services/user.service';
import { ActivatedRoute, Router } from '@angular/router';


@Component({
  selector: 'app-edit-profile',
  templateUrl: './edit-profile.page.html',
  styleUrls: ['./edit-profile.page.scss'],
})
export class EditProfilePage implements OnInit {
  profileForm: FormGroup;
  previewImage: string | null = '../../assets/images/user.png'; // 默认头像路径
  selectedFile: File | null = null;

  constructor(
    private fb: FormBuilder,
    private navCtrl: NavController,
    private userService: UserService,
    private router: Router,
    private platform: Platform
  ) {
    // 初始化表单，并为 userAvatar 设置默认值
    this.profileForm = this.fb.group({
      username: ['', [Validators.required]],
      email: ['', [Validators.required, Validators.email]],
      phone: ['', [Validators.required, Validators.pattern('^[0-9]*$')]],
      gender: ['', [Validators.required]],
      birthday: ['', [Validators.required]],
      userAvatar: ['../../assets/images/user-avatar.png', []] as [string | null, Validators[]] // 设置默认值并明确类型
    });

    // 预填充表单（如果有初始用户信息）
    this.userService.getUserInfo().subscribe(userInfo => {
      if (userInfo) {
        this.profileForm.patchValue(userInfo);
        this.previewImage = userInfo.userAvatar ?? '../../assets/images/user.png'; // 确保预览图像是最新的头像或默认值
      }
    });
  }

  ngOnInit() {
    // 如果需要在页面加载时执行额外的初始化逻辑，可以在这里添加
  }

  onFileSelected(event: Event) {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
      const file = input.files[0];
      const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];

      if (allowedTypes.includes(file.type)) {
        this.readFileAsBase64(file).then(base64Data => {
          this.selectedFile = file;
          this.previewImage = base64Data; // 设置预览图
          this.profileForm.patchValue({ userAvatar: base64Data }); // 更新表单中的头像字段
        }).catch(error => {
          console.error('Failed to read file as Base64:', error);
        });
      } else {
        alert('请选择有效的图片文件（支持的格式：JPEG, PNG, GIF）。');
        input.value = '';
        this.selectedFile = null;
        this.previewImage = '../../assets/images/user.png'; // 清除预览图并恢复默认值
      }
    }
  }

  saveProfile() {
    if (this.profileForm.valid) {
      const updatedUserInfo = this.profileForm.value;
      console.log('Profile saved:', updatedUserInfo);
  
      // 更新用户信息
      this.userService.updateUserInfo(updatedUserInfo).then(() => {
        this.navigateToTab3(); // 保存成功后跳转到 tab3 页面
      }).catch(error => {
        console.error('Failed to update user info:', error);
      });
    } else {
      console.warn('Form is invalid. Please check the inputs.');
      Object.keys(this.profileForm.controls).forEach(key => {
        const control = this.profileForm.get(key);
        if (control?.invalid) {
          console.warn(`Invalid ${key}:`, control.errors);
        }
      });
    }
  }

  private async readFileAsBase64(file: File): Promise<string> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onloadend = () => resolve(reader.result as string || '');
      reader.onerror = reject;
      reader.readAsDataURL(file); // 读取文件为 Base64 编码的字符串
    });
  }

  private navigateToTab3() {
    this.router.navigate(['/tabs/tab3']);
  }
}