import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AlertController } from '@ionic/angular';
import { CloudUser } from 'src/lib/ncloud'; // 确保路径正确

@Component({
  selector: 'app-tab4',
  templateUrl: './tab4.page.html',
  styleUrls: ['./tab4.page.scss'],
  standalone: false,
})
export class Tab4Page {
  isLoggedIn = false; // 初始状态为未登录
  user = {
    name: '未登录',
    avatar: 'assets/icon/default-avatar.png',
    type: '',
    fields: 0,
    solved: 0,
    exp: 0
  };

  private cloudUser = new CloudUser(); // 创建CloudUser实例

  constructor(
    private router: Router,
    private alertCtrl: AlertController
  ) {
    this.checkLoginStatus(); // 初始化时检查登录状态
  }

  // 检查登录状态
  private async checkLoginStatus() {
    const currentUser = await this.cloudUser.current();
    if (currentUser) {
      this.isLoggedIn = true;
      this.updateUserData(currentUser);
    }
  }

  // 更新用户数据
  private updateUserData(userData: any) {
    // 确保username存在，如果不存在则显示"未命名用户"
    const username = userData.data.username || '未命名用户';
    
    this.user = {
      name: username, // 直接使用用户名，不使用默认值"爱睡觉的"
      avatar: userData.data.avatar || 'assets/icon/farmer-avatar.png',
      type: userData.data.type || 'farmer',
      fields: userData.data.fields || 0,
      solved: userData.data.solved || 0,
      exp: userData.data.exp || 0
    };
  }

  // 导航到设置页面
  goToSettings() {
    this.router.navigate(['/settings']);
  }

  // 导航到登录页面
  async login() {
    const alert = await this.alertCtrl.create({
      header: '登录',
      inputs: [
        {
          name: 'username',
          type: 'text',
          placeholder: '用户名'
        },
        {
          name: 'password',
          type: 'password',
          placeholder: '密码'
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '登录',
          handler: async (data) => {
            if (!data.username || !data.password) {
              this.showAlert('错误', '用户名和密码不能为空');
              return false;
            }
            
            const loadingAlert = await this.alertCtrl.create({
              message: '登录中...'
            });
            await loadingAlert.present();

            try {
              const user = await this.cloudUser.login(data.username, data.password);
              loadingAlert.dismiss();
              if (user) {
                this.isLoggedIn = true;
                this.updateUserData(user);
                this.showAlert('成功', '登录成功');
                return true;
              } else {
                this.showAlert('错误', '用户名或密码错误');
                return false;
              }
            } catch (error) {
              loadingAlert.dismiss();
              this.showAlert('错误', '登录失败，请稍后重试');
              return false;
            }
          }
        }
      ]
    });
    await alert.present();
  }

  // 导航到注册页面
  async signUp() {
    const alert = await this.alertCtrl.create({
      header: '注册',
      inputs: [
        {
          name: 'username',
          type: 'text',
          placeholder: '用户名'
        },
        {
          name: 'password',
          type: 'password',
          placeholder: '密码'
        },
        {
          name: 'confirmPassword',
          type: 'password',
          placeholder: '确认密码'
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '注册',
          handler: async (data) => {
            if (!data.username || !data.password || !data.confirmPassword) {
              this.showAlert('错误', '请填写完整信息');
              return false;
            }
            
            if (data.password !== data.confirmPassword) {
              this.showAlert('错误', '两次输入的密码不一致');
              return false;
            }

            const loadingAlert = await this.alertCtrl.create({
              message: '注册中...'
            });
            await loadingAlert.present();

            try {
              const user = await this.cloudUser.signUp(data.username, data.password);
              loadingAlert.dismiss();
              if (user) {
                this.isLoggedIn = true;
                this.updateUserData({
                  data: {
                    ...user.data,
                    username: data.username // 明确传递用户名
                  }
                });
                this.showAlert('成功', '注册成功');
                return true;
              } else {
                this.showAlert('错误', '注册失败，用户名可能已被占用');
                return false;
              }
            } catch (error) {
              loadingAlert.dismiss();
              this.showAlert('错误', '注册失败，请稍后重试');
              return false;
            }
          }
        }
      ]
    });
    await alert.present();
  }

  // 导航到农田管理
  goToFields() {
    if (!this.isLoggedIn) {
      this.showLoginPrompt();
      return;
    }
    this.router.navigate(['/my-fields']);
  }

  // 导航到我的提问
  goToQuestions() {
    if (!this.isLoggedIn) {
      this.showLoginPrompt();
      return;
    }
    this.router.navigate(['/my-questions']);
  }

  // 导航到收藏
  goToFavorites() {
    if (!this.isLoggedIn) {
      this.showLoginPrompt();
      return;
    }
    this.router.navigate(['/favorites']);
  }

  // 导航到反馈
  goToFeedback() {
    this.router.navigate(['/feedback']);
  }

  // 导航到关于我们
  goToAbout() {
    this.router.navigate(['/about']);
  }

  // 退出登录
  async logout() {
    const alert = await this.alertCtrl.create({
      header: '确认退出',
      message: '确定要退出当前账号吗？',
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '退出',
          handler: async () => {
            const success = await this.cloudUser.logout();
            if (success) {
              this.isLoggedIn = false;
              this.user = {
                name: '未登录',
                avatar: 'assets/icon/default-avatar.png',
                type: '',
                fields: 0,
                solved: 0,
                exp: 0
              };
              this.showAlert('成功', '已退出登录');
            } else {
              this.showAlert('错误', '退出登录失败');
            }
          }
        }
      ]
    });
    await alert.present();
  }

  // 显示提示登录的对话框
  private async showLoginPrompt() {
    const alert = await this.alertCtrl.create({
      header: '需要登录',
      message: '此功能需要登录后才能使用',
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '去登录',
          handler: () => {
            this.login();
          }
        }
      ]
    });
    await alert.present();
  }

  // 显示通用提示框
  private async showAlert(header: string, message: string) {
    const alert = await this.alertCtrl.create({
      header,
      message,
      buttons: ['确定']
    });
    await alert.present();
  }
}