import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-auth',
  standalone: true,
  imports: [CommonModule, IonicModule, ReactiveFormsModule], // ✅ 添加 ReactiveFormsModule
  templateUrl: './auth.page.html',
  styleUrls: ['./auth.page.scss']
})
export class AuthPage {
  authForm: FormGroup;
  isLoginMode = true; // true: 登录，false: 注册
  errorMessage = '';

  constructor(private fb: FormBuilder, private router: Router) {
    this.authForm = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(6)]],
      confirmPassword: ['']
    }, { validators: this.passwordsMatchValidator });
  }

  switchMode() {
    this.isLoginMode = !this.isLoginMode;
    this.errorMessage = '';
    if (!this.isLoginMode) {
      this.authForm.get('confirmPassword')?.setValidators([Validators.required]);
    } else {
      this.authForm.get('confirmPassword')?.clearValidators();
    }
    this.authForm.get('confirmPassword')?.updateValueAndValidity();
  }

  passwordsMatchValidator(form: FormGroup) {
    if (
      form.get('password')?.value !== form.get('confirmPassword')?.value &&
      !form.get('confirmPassword')?.pristine
    ) {
      return { mismatch: true };
    }
    return null;
  }

  onSubmit() {
    if (!this.authForm.valid) {
      this.errorMessage = '请填写完整且有效的信息';
      return;
    }

    const email = this.authForm.value.email;
    const password = this.authForm.value.password;

    if (this.isLoginMode) {
      if (email === '2013301993@qq.com') {
        this.errorMessage = '';
        alert('登录成功！');
        this.router.navigate(['/tab5']);
      } else {
        this.errorMessage = '邮箱或密码错误';
      }
    } else {
      alert(`注册成功！邮箱：${email}`);
      this.switchMode();
    }
  }

  get email() {
    return this.authForm.get('email');
  }

  get password() {
    return this.authForm.get('password');
  }

  get confirmPassword() {
    return this.authForm.get('confirmPassword');
  }
}
