import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router, RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { CloudObject, CloudQuery, CloudUser } from '../../../lib/ncloud';

@Component({
  selector: 'app-nav-pc-top-menu',
  standalone: true,
  imports: [CommonModule, RouterModule, FormsModule],
  templateUrl: './nav-pc-top-menu.html',
  styleUrls: ['./nav-pc-top-menu.scss']
})
export class NavPcTopMenu implements OnInit {
  user: CloudUser | null = null;
  userAvatar: string | null = null;
  userInitials: string = '';
  loginError: string = '';
  registerError: string = '';
  isLoading: boolean = true;
  showMenu: boolean = false;
  emailError: boolean = false;
  
  // 登录注册模态框相关
  showAuthModal: boolean = false;
  authType: 'login' | 'register' = 'login';
  
  // 登录表单
  loginIdentifier: string = '';
  loginPassword: string = '';
  rememberMe: boolean = true;
  isLoggingIn: boolean = false;

  
  // 注册表单
  registerUsername: string = '';
  registerEmail: string = '';
  registerPhone: string = '';
  registerPassword: string = '';
  registerPasswordConfirm: string = '';
  acceptTerms: boolean = false;
  isRegistering: boolean = false;

  constructor(private router: Router) {}

  async ngOnInit() {
    // 尝试获取当前用户
    try {
      this.user = new CloudUser();
      const currentUser = await this.user.current();
      
      if (currentUser && this.user.id) {
        this.user = currentUser;
        this.generateUserInitials();
      } else {
        this.user = null;
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      this.user = null;
    } finally {
      this.isLoading = false;
    }
  }

  // 生成用户头像首字母
  generateUserInitials() {
    if (!this.user) return;
    
    const username = this.user.get('username') || '';
    if (username.length > 0) {
      this.userInitials = username.charAt(0).toUpperCase();
    }
    
    // 如果有头像URL，则设置
    const avatar = this.user.get('avatar');
    if (avatar && typeof avatar === 'string') {
      this.userAvatar = avatar;
    }
  }

  toggleMenu() {
    this.showMenu = !this.showMenu;
  }

 openAuthModal(type: 'login' | 'register') {
    this.authType = type;
    this.showAuthModal = true;
    this.showMenu = false;
    this.loginError = '';
    this.registerError = '';
    this.emailError = false;
}
  closeAuthModal() {
    this.showAuthModal = false;
    this.isLoggingIn = false;
    this.isRegistering = false;
  }

  setAuthType(type: 'login' | 'register') {
    this.authType = type;
  }

async login() {
    if (!this.loginIdentifier || !this.loginPassword) {
        this.loginError = '请输入用户名/手机号/邮箱和密码';
        return;
    }
    
    this.isLoggingIn = true;
    this.loginError = '';
    
    try {
      const user = new CloudUser();
      const loggedIn = await user.login(
        this.loginIdentifier, 
        this.loginPassword
      );
      
      if (loggedIn) {
        this.user = loggedIn;
        this.generateUserInitials();
        this.closeAuthModal();
      } else {
        this.loginError = '用户名或密码错误';
      }
    } catch (error: any) {
            this.loginError = error.message || '登录失败，请稍后重试';
        } finally {
            this.isLoggingIn = false;
        }
    }


  async register() {
    // 重置错误状态
    this.registerError = '';
    this.emailError = false;
    // 表单验证
    if (!this.registerUsername) {
      alert('请输入用户名');
      return;
    }
    
    if (!this.registerEmail) {
      alert('请输入邮箱');
      return;
    }else {
      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (!emailRegex.test(this.registerEmail)) {
        this.emailError = true;
        this.registerError = '邮箱格式不正确';
        return;
      }
    }
    
    if (!this.registerPassword) {
      alert('请输入密码');
      return;
    }
    
    if (this.registerPassword !== this.registerPasswordConfirm) {
      alert('两次输入的密码不一致');
      return;
    }
    
    if (!this.acceptTerms) {
      alert('请阅读并同意用户协议和隐私政策');
      return;
    }
    
this.isRegistering = true;
        
        try {
            const user = new CloudUser();
            const newUser = await user.signUp(
                this.registerUsername, 
                this.registerPassword, 
                {
                    email: this.registerEmail,
                    phone: this.registerPhone
                }
            );
            
            if (newUser) {
                this.user = newUser;
                this.generateUserInitials();
                this.closeAuthModal();
            }
            this.loginIdentifier = this.registerEmail || this.registerPhone || this.registerUsername;
        this.loginPassword = this.registerPassword;
        await this.login();
        } catch (error: any) {
            this.registerError = error.message || '注册失败';
        } finally {
            this.isRegistering = false;
        }
    }


  async logout() {
    if (!this.user) return;
    
    try {
      await this.user.logout();
      this.user = null;
      this.userAvatar = null;
      this.userInitials = '';
      this.showMenu = false;
      this.router.navigate(['/home']);
    } catch (error) {
      console.error('退出登录失败:', error);
      alert('退出登录失败: ' + (error instanceof Error ? error.message : '未知错误'));
    }
  }
}