import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { IonRouterOutlet, ModalController } from '@ionic/angular';
import { CloudQuery, CloudUser } from 'src/lib/ncloud';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AlertController, LoadingController } from '@ionic/angular';

@Component({
  selector: 'app-mine',
  templateUrl: './mine.page.html',
  styleUrls: ['./mine.page.scss'],
})
export class MinePage implements OnInit {

  currentUser: CloudUser | null = null;
  isLoginMode = true;
  isLoading = false;
  profileForm!: FormGroup;
  
  credentials = {
    username: '',
    password: '',
    confirmPassword: ''
  };
   constructor(
    private alertCtrl: AlertController,
    private loadingCtrl: LoadingController,
    private formBuilder: FormBuilder
  ) {
    this.initializeUser();
    this.createForm();
  }

  async initializeUser() {
    this.currentUser = new CloudUser();
    const user = await this.currentUser.current();
    if (user?.id) {
      this.currentUser = user;
      this.updateFormWithUserData();
    } else {
      this.currentUser = null;
    }
  }

  createForm() {
    this.profileForm = this.formBuilder.group({
      username: ['', Validators.required],
      email: ['', [Validators.email]],
      phone: [''],
      // Add other user fields as needed
    });
  }

  updateFormWithUserData() {
    if (this.currentUser) {
      this.profileForm.patchValue({
        username: this.currentUser.get('username'),
        email: this.currentUser.get('email'),
        phone: this.currentUser.get('phone')
      });
    }
  }

  async onLogin() {
    if (!this.credentials.username || !this.credentials.password) {
      this.showAlert('登录失败', '请输入用户名和密码');
      return;
    }

    this.isLoading = true;
    const loading = await this.loadingCtrl.create({
      message: '登录中...'
    });
    await loading.present();

    try {
      const user = new CloudUser();
      const loggedInUser = await user.login(
        this.credentials.username,
        this.credentials.password
      );
      
      if (loggedInUser?.id) {
        this.currentUser = loggedInUser;
        this.updateFormWithUserData();
        this.resetCredentials();
      } else {
        this.showAlert('登录失败', '用户名或密码不正确');
      }
    } catch (error) {
      const err = error as { message?: string };
      console.error('登录错误:', err);
      this.showAlert('登录错误', err.message || '登录过程中发生错误');
    } finally {
      this.isLoading = false;
      await loading.dismiss();
    }
  }

  async onRegister() {
    if (this.credentials.password !== this.credentials.confirmPassword) {
      this.showAlert('注册失败', '两次输入的密码不一致');
      return;
    }

    if (!this.credentials.username || !this.credentials.password) {
      this.showAlert('注册失败', '请输入用户名和密码');
      return;
    }

    this.isLoading = true;
    const loading = await this.loadingCtrl.create({
      message: '注册中...'
    });
    await loading.present();

    try {
      // Check if username exists
      const query = new CloudQuery('_User');
      query.equalTo('username', this.credentials.username);
      const existingUser = await query.first();
      
      if (existingUser) {
        this.showAlert('注册失败', '该用户名已被使用');
        return;
      }

      // Create new user using the signUp method from CloudUser
      const newUser = await new CloudUser().signUp(
        this.credentials.username,
        this.credentials.password
      );
      
      if (newUser?.id) {
        this.currentUser = newUser;
        this.updateFormWithUserData();
        this.resetCredentials();
        this.showAlert('注册成功', '您的账号已成功创建');
      } else {
        this.showAlert('注册失败', '创建用户时发生错误');
      }
    } catch (error) {
      const err = error as { message?: string };
      console.error('注册错误:', err);
      this.showAlert('注册错误', err.message || '注册过程中发生错误');
    } finally {
      this.isLoading = false;
      await loading.dismiss();
    }
  }

  async updateProfile() {
    if (!this.currentUser || !this.profileForm.valid) {
      return;
    }

    this.isLoading = true;
    const loading = await this.loadingCtrl.create({
      message: '更新中...'
    });
    await loading.present();

    try {
      // Update user data
      const formData = this.profileForm.value;
      Object.keys(formData).forEach(key => {
        if (formData[key] !== undefined && formData[key] !== null) {
          this.currentUser?.set({ [key]: formData[key] });
        }
      });

      // Save changes
      const updatedUser = await this.currentUser.save();
      
      if (updatedUser?.id) {
        this.showAlert('更新成功', '您的资料已更新');
      } else {
        this.showAlert('更新失败', '更新用户资料时发生错误');
      }
    } catch (error) {
      const err = error as { message?: string };
      console.error('更新错误:', err);
      this.showAlert('更新错误', err.message || '更新过程中发生错误');
    } finally {
      this.isLoading = false;
      await loading.dismiss();
    }
  }

  async logout() {
    this.isLoading = true;
    const loading = await this.loadingCtrl.create({
      message: '登出中...'
    });
    await loading.present();

    try {
      if (this.currentUser) {
        await this.currentUser.logout();
        this.currentUser = null;
        this.profileForm.reset();
      }
    } catch (error) {
      console.error('登出错误:', error);
      this.showAlert('登出错误', '登出过程中发生错误');
    } finally {
      this.isLoading = false;
      await loading.dismiss();
    }
  }

  resetCredentials() {
    this.credentials = {
      username: '',
      password: '',
      confirmPassword: ''
    };
  }

  async showAlert(header: string, message: string) {
    const alert = await this.alertCtrl.create({
      header,
      message,
      buttons: ['确定']
    });
    await alert.present();
  }

  toggleAuthMode() {
    this.isLoginMode = !this.isLoginMode;
    this.resetCredentials();
  }

  ngOnInit() {}
}
