import { Component, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Router, RouterModule } from '@angular/router';
import { HttpClient, HttpClientModule } from '@angular/common/http';

@Component({
  selector: 'app-auth',
  standalone: true,
  imports: [CommonModule, FormsModule, RouterModule, HttpClientModule],
  templateUrl: './auth.html',
  styleUrls: ['./auth.scss']
})
export class Auth {
  constructor(private router: Router, private http: HttpClient) {}

  // 使用signal管理状态
  isLoginMode = signal(true);
  username = signal('');
  password = signal('');
  errorMessage = signal('');
  successMessage = signal('');

  // 切换登录/注册模式
  toggleMode() {
    this.isLoginMode.set(!this.isLoginMode());
    this.errorMessage.set('');
    this.successMessage.set('');
  }

  // 处理表单提交
  onSubmit() {
    if (this.isLoginMode()) {
      this.handleLogin();
    } else {
      this.handleRegister();
    }
  }

  // 登录逻辑
  private handleLogin() {
    this.http.post<any>('http://localhost:3000/api/login', {
      username: this.username(),
      password: this.password()
    }).subscribe({
      next: (response) => {
        if (response.success) {
          this.successMessage.set('登录成功! 欢迎回来，' + this.username());
          this.errorMessage.set('');
          this.router.navigate(['/intervieweeauth/home']);
        } else {
          this.errorMessage.set(response.message);
        }
      },
      error: (error) => {
        this.errorMessage.set('登录失败，请稍后再试');
      }
    });
  }

  // 注册逻辑
  private handleRegister() {
    this.http.post<any>('http://localhost:3000/api/register', {
      username: this.username(),
      password: this.password()
    }).subscribe({
      next: (response) => {
        if (response.success) {
          this.successMessage.set('注册成功! 您现在可以登录了');
          this.errorMessage.set('');
          this.isLoginMode.set(true); // 自动切换到登录模式
        } else {
          this.errorMessage.set(response.message);
        }
      },
      error: (error) => {
        this.errorMessage.set('注册失败，请稍后再试');
      }
    });
  }
}