// login.page.ts
import { Component } from '@angular/core';
import { AuthService } from 'src/app/services/auth.service';
import { Router } from '@angular/router';
import { ToastController } from '@ionic/angular';
import { NavController } from '@ionic/angular';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
  standalone:false,
})
export class LoginPage {

  username = '';
  password = '';
  email = '';
  isLogin = true;
  isLoading = false; // 添加加载状态

  constructor(
    private authService: AuthService,
    private router: Router,
    private toastCtrl: ToastController
  ) {}

  async submit() {
    if (this.isLoading) return;
    
    this.isLoading = true;
    
    try {
      if (this.isLogin) {
        await this.handleLogin();
      } else {
        await this.handleRegister();
      }
    } catch (error) {
      console.error('Auth error:', error);
      this.showToast('操作失败，请稍后重试');
    } finally {
      this.isLoading = false;
    }
  }

  private async handleLogin() {
    if (!this.username || !this.password) {
      this.showToast('请输入用户名和密码');
      return;
    }

    const success = await this.authService.login(this.username, this.password);
    
    if (success) {
      this.showToast('登录成功');
      this.router.navigate(['/tabs/tab4'], { replaceUrl: true });
    } else {
      this.showToast('登录失败，请检查用户名和密码');
    }
  }

  private async handleRegister() {
    if (!this.username || !this.password) {
      this.showToast('请输入用户名和密码');
      return;
    }

    const success = await this.authService.register(
      this.username, 
      this.password, 
      this.email || undefined
    );

    if (success) {
      this.showToast('注册成功，已自动登录');
      this.router.navigate(['/tabs/tab1'], { replaceUrl: true });
    } else {
      this.showToast('注册失败，用户名可能已被使用');
    }
  }


  toggleMode() {
    this.isLogin = !this.isLogin;
  }

  private async showToast(message: string) {
    const toast = await this.toastCtrl.create({
      message,
      duration: 2000,
      position: 'top'
    });
    await toast.present();
  }
}