import { Component, Input, OnInit } from '@angular/core';
import { IonButton, IonCard, IonCardContent, IonCardHeader, IonCardSubtitle, IonCardTitle, IonContent, IonHeader, IonInput, IonItem, IonLabel, IonSegment, IonSegmentButton, IonTitle, IonToolbar, ModalController } from '@ionic/angular/standalone';
import { CloudUser } from '../../ncloud';
import { ModalUserLoginComponent } from 'fmode-ng';

@Component({
  selector: 'model-user-login',
  templateUrl: './model-user-login.component.html',
  styleUrls: ['./model-user-login.component.scss'],
  standalone: true,
  imports: [IonHeader, IonToolbar, IonTitle, IonContent, IonCard, IonCardContent,
    IonButton, IonCardHeader, IonCardTitle, IonCardSubtitle, IonInput, IonItem,
    IonSegment, IonSegmentButton, IonLabel,
  ],
})
export class ModelUserLoginComponent implements OnInit {
  @Input()
  type: "login" | "signup" = "login"
  typeChange(ev: any) {
    this.type = ev?.detail?.value || ev?.value || 'login'
  }
  username: string = ""
  usernameChange(ev: any) {
    console.log(ev)
    this.username = ev?.detail?.value
  }
  password: string = ""
  passwordChange(ev: any) {
    this.password = ev?.detail?.value
  }
  password2: string = ""
  password2Change(ev: any) {
    this.password2 = ev?.detail?.value
  }
  constructor(private modalCtrl: ModalController) { }

  ngOnInit() { }

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

  async signup() {
    if (!this.username || !this.password || !this.password2) {
      console.log("请输入完整")
      return
    }
    if (this.password != this.password2) {
      console.log("两次密码不符，请修改")
      return
    }

    let user: any = new CloudUser();
    user = await user.signUp(this.username, this.password);
    if (user) {
      this.type = "login"
      console.log("注册成功请登录")
    }
  }


}

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.5, 0.7],
    initialBreakpoint: 0.5
  });
  modal.present();

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

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