import { Input, OnInit } from '@angular/core';
import { Component } from '@angular/core';
import { IonButtons, IonIcon, IonText, ModalController } from '@ionic/angular/standalone';
import { IonButton, IonCard, IonCardContent, IonCardHeader, IonCardSubtitle, IonCardTitle, IonCol, IonContent, IonHeader, IonInput, IonItem, IonLabel, IonRow, IonTitle, IonToolbar } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { arrowBack, arrowBackOutline, chevronBack } from 'ionicons/icons';
import { CloudUser } from 'src/lib/ncloud';

@Component({
  selector: 'app-modal-user-login',
  templateUrl: './modal-user-login.component.html',
  styleUrls: ['./modal-user-login.component.scss'],
  standalone: true,
  imports:[IonLabel,IonCol,IonRow,IonButton,IonInput,IonItem,IonCardContent,IonCardSubtitle,IonCardTitle,IonCardHeader,IonContent,IonTitle,IonCard,IonToolbar,IonHeader,IonIcon,IonButtons
    ,IonText
  ]
})
export class ModalUserLoginComponent implements OnInit {
  @Input() type: "login" | "signup" = "login"; // 登录或注册状态
  username: string = ""; // 用户名
  password: string = ""; // 密码
  password2: string = ""; // 确认密码

  constructor(private modalCtrl: ModalController) {
    addIcons({chevronBack,arrowBack});
  }

  ngOnInit() {}

  // 输入框值变化
  usernameChange(ev: any) {
    this.username = ev?.detail?.value || '';
  }

  passwordChange(ev: any) {
    this.password = ev?.detail?.value || '';
  }

  password2Change(ev: any) {
    this.password2 = ev?.detail?.value || '';
  }

  // 登录功能
  async login() {
    if (!this.username || !this.password) {
      console.log("请输入完整");
      return;
    }
    const user = new CloudUser();
    const result = await user.login(this.username, this.password);
    if (result?.id) {
      this.modalCtrl.dismiss(result, "confirm");
    } else {
      console.log("登录失败");
    }
  }

  // 注册功能
  async signup() {
    if (!this.username || !this.password || !this.password2) {
      console.log("请输入完整");
      return;
    }
    if (this.password !== this.password2) {
      console.log("两次密码不符，请修改");
      return;
    }
    const user = new CloudUser();
    const result = await user.signUp(this.username, this.password);
    if (result) {
      this.type = "login";
      console.log("注册成功，请登录");
    }
  }

  // 切换登录/注册
  toggleType() {
    this.type = this.type === 'login' ? 'signup' : 'login';
  }

  dismissModal() {
    this.modalCtrl.dismiss();
  }
}

export async function openUserLoginModal(modalCtrl: ModalController, type: "login" | "signup" = "login"): Promise<CloudUser | null> {
  const modal = await modalCtrl.create({
    component: ModalUserLoginComponent,
    componentProps: { type }
  });
  await modal.present();
  
  const { data, role } = await modal.onWillDismiss();
  if (role === 'confirm') {
    return data;
  }
  return null;
}
