import { Component, Input, OnInit, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { IonButton, IonCard, IonCardContent, IonCardHeader, IonCardSubtitle, IonCardTitle, IonContent, IonHeader, IonInput, IonItem, IonLabel, IonSegment, IonSegmentButton, IonTitle, IonToolbar, ModalController, ToastController, IonIcon } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { personOutline, lockClosedOutline } from 'ionicons/icons';
import { CloudUser } from '../../ncloud';

@Component({
  selector: 'model-user-login',
  templateUrl: './model-user-login.component.html',
  styleUrls: ['./model-user-login.component.scss'],
  standalone: true,
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  imports: [
    FormsModule,
    IonHeader,
    IonToolbar,
    IonTitle,
    IonContent,
    IonCard,
    IonCardContent,
    IonButton,
    IonCardHeader,
    IonCardTitle,
    IonCardSubtitle,
    IonInput,
    IonItem,
    IonSegment,
    IonSegmentButton,
    IonLabel,
    IonIcon
  ],
})
export class ModelUserLoginComponent implements OnInit {
  @Input()
  type: "login" | "signup" = "login"

  // 添加回 typeChange 方法
  typeChange(ev: any) {
    this.type = ev?.detail?.value || ev?.value || 'login';
    // 切换类型时清空错误信息和密码
    this.errorMessage = '';
    this.password = '';
    this.password2 = '';
  }

  // 添加 isSignup 计算属性
  get isSignup(): boolean {
    return this.type === 'signup';
  }

  username: string = ""
  password: string = ""
  password2: string = ""
  errorMessage: string = ""

  constructor(
    private modalCtrl: ModalController,
    private toastCtrl: ToastController
  ) {
    addIcons({
      'person-outline': personOutline,
      'lock-closed-outline': lockClosedOutline
    });
  }

  ngOnInit() { }

  // 验证用户名
  validateUsername(): boolean {
    if (!this.username) {
      this.showError('用户名不能为空');
      return false;
    }
    if (this.username.length < 3) {
      this.showError('用户名长度不能少于3个字符');
      return false;
    }
    if (this.username.length > 20) {
      this.showError('用户名长度不能超过20个字符');
      return false;
    }
    if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(this.username)) {
      this.showError('用户名只能包含字母、数字、下划线和中文');
      return false;
    }
    return true;
  }

  // 验证密码
  validatePassword(): boolean {
    if (!this.password) {
      this.showError('密码不能为空');
      return false;
    }
    if (this.password.length < 6) {
      this.showError('密码长度不能少于6个字符');
      return false;
    }
    if (this.password.length > 20) {
      this.showError('密码长度不能超过20个字符');
      return false;
    }
    if (!/^[a-zA-Z0-9_]+$/.test(this.password)) {
      this.showError('密码只能包含字母、数字和下划线');
      return false;
    }
    return true;
  }

  // 验证确认密码
  validateConfirmPassword(): boolean {
    if (this.password !== this.password2) {
      this.showError('两次输入的密码不一致');
      return false;
    }
    return true;
  }

  async showError(message: string) {
    this.errorMessage = message;
    const toast = await this.toastCtrl.create({
      message: message,
      duration: 2000,
      position: 'top',
      color: 'danger',
      cssClass: 'error-toast'
    });
    await toast.present();
  }

  async showSuccess(message: string) {
    const toast = await this.toastCtrl.create({
      message: message,
      duration: 2000,
      position: 'top',
      color: 'success',
      cssClass: 'success-toast'
    });
    await toast.present();
  }

  async login() {
    this.errorMessage = '';
    if (!this.validateUsername() || !this.validatePassword()) {
      return;
    }

    try {
      let user: any = new CloudUser();
      user = await user.login(this.username, this.password);
      if (user?.id) {
        await this.showSuccess('登录成功');
        this.modalCtrl.dismiss(user, "confirm");
      } else {
        this.showError('用户名或密码错误');
      }
    } catch (error) {
      this.showError('登录失败，请稍后重试');
    }
  }

  async signup() {
    this.errorMessage = '';
    if (!this.validateUsername() || !this.validatePassword() || !this.validateConfirmPassword()) {
      return;
    }

    try {
      let user: any = new CloudUser();
      user = await user.signUp(this.username, this.password);
      if (user) {
        await this.showSuccess('注册成功，请登录');
        this.type = "login";
        this.password = '';
        this.password2 = '';
      } else {
        this.showError('注册失败，该用户名可能已被使用');
      }
    } catch (error) {
      this.showError('注册失败，请稍后重试');
    }
  }


}

export async function openUserLoginModal(modalCtrl: ModalController, type: "login" | "signup" = "login"): Promise<CloudUser | null> {
  const modal = await modalCtrl.create({
    component: ModelUserLoginComponent,
    componentProps: {
      type: type
    },
    breakpoints: [0, 0.6, 0.8],
    initialBreakpoint: 0.6,
    backdropBreakpoint: 0.6,
    cssClass: 'login-modal'
  });
  modal.present();

  const { data, role } = await modal.onWillDismiss();

  if (role === 'confirm') {
    return data;
  }
  return null
}