// src/app/login/login.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router'; // 导入 Router 模块
import { IonicModule, IonContent, IonHeader, IonToolbar, IonButtons, IonMenuButton, IonButton, IonIcon, IonLabel, IonInput, IonItem,  } from '@ionic/angular';
import { FormsModule } from '@angular/forms'; // 导入 FormsModule
import { CloudUser } from 'src/lib/ncloud';
import { openUserLoginModal } from 'src/lib/user/modal-user-login/modal-user-login.component';
import { openUserEditModal } from 'src/lib/user/modal-user-edit/modal-user-edit.component';
import { addIcons } from 'ionicons';
import { folderOutline, timeOutline, starOutline, heartOutline, chevronForwardOutline, personOutline, shieldOutline, callOutline, lockClosedOutline } from 'ionicons/icons';
import { ModalController } from '@ionic/angular/standalone';
import { AlertController } from '@ionic/angular/standalone'; // 导入所需的模块

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  standalone: true,
  imports: [IonicModule, FormsModule], // 确保导入 FormsModule
})
export class LoginComponent {
  username: string = '';
  password: string = '';
  currentUser: CloudUser | undefined;
  isRegistered: boolean = false;
  showLoginForm: boolean = false;

  constructor(
    private router: Router,
    private alertController: AlertController,
    private modalCtrl: ModalController
  ) {
    addIcons({ folderOutline, timeOutline, starOutline, heartOutline, chevronForwardOutline, personOutline, shieldOutline, callOutline, lockClosedOutline });
    this.currentUser = new CloudUser();
  }

  async onSubmit() {
    // 处理登录逻辑
    console.log('Username:', this.username);
    console.log('Password:', this.password);

    // 示例：成功登录后导航到主页或其他页面
    if (this.username && this.password) {
      // 这里可以添加实际的登录验证逻辑
      this.currentUser = new CloudUser(); // 假设登录成功
      this.router.navigate(['/tab3']); // 假设主页面是 tabs/tab3
    }
  }

  async login() {
    // 弹出登录窗口
    let user = await openUserLoginModal(this.modalCtrl);
    if (user?.id) {
      this.currentUser = user;
      this.showLoginForm = false; // 关闭登录表单
      this.router.navigate(['/tabs/tab3']);
    }
  }

  async signup() {
    // 弹出注册窗口
    let user = await openUserLoginModal(this.modalCtrl, "signup");
    if (user?.id) {
      this.isRegistered = true; // 设置注册状态为已注册
      this.currentUser = user;
      this.showLoginForm = false; // 关闭登录表单
    }
  }

  logout() {
    this.currentUser?.logout();
    this.isRegistered = false; // 设置注册状态为未注册
    this.showLoginForm = false; // 关闭登录表单
  }


  toggleLoginForm(show: boolean) {
    this.showLoginForm = show;
  }
}
