import { Component, OnInit } from '@angular/core';
import {
  IonHeader, IonToolbar, IonTitle, IonContent,
  IonButton, IonInput, IonItem, IonList, IonIcon,
  IonSegment, IonSegmentButton, IonLabel, IonButtons
} from '@ionic/angular/standalone';
import { ModalController } from '@ionic/angular/standalone';
import { CloudUser } from 'src/lib/ncloud';
import { addIcons } from 'ionicons';
import {
  closeOutline, saveOutline, personOutline,
  idCardOutline, calendarOutline, transgenderOutline,
  imageOutline
} from 'ionicons/icons';

@Component({
  selector: 'app-modal-user-edit',
  templateUrl: './modal-user-edit.component.html',
  styleUrls: ['./modal-user-edit.component.scss'],
  standalone: true,
  imports: [
    IonHeader, IonToolbar, IonTitle, IonContent,
    IonButton, IonInput, IonItem, IonList, IonIcon,
    IonSegment, IonSegmentButton, IonLabel, IonButtons
  ],
})
export class ModalUserEditComponent implements OnInit {
  currentUser: CloudUser | undefined;
  userData: any = {};

  constructor(private modalCtrl: ModalController) {
    this.currentUser = new CloudUser();
    this.userData = { ...this.currentUser.data };
    addIcons({
      closeOutline, saveOutline, personOutline,
      idCardOutline, calendarOutline, transgenderOutline,
      imageOutline
    });
  }

  userDataChange(key: string, ev: any) {
    let value = ev?.detail?.value;
    if (value) {
      this.userData[key] = value;
    }
  }

  ngOnInit() { }

  async save() {
    Object.keys(this.userData).forEach(key => {
      if (key == "age") {
        this.userData[key] = Number(this.userData[key]);
      }
    });

    this.currentUser?.set(this.userData);
    await this.currentUser?.save();
    this.modalCtrl.dismiss(this.currentUser, "confirm");
  }

  cancel() {
    this.modalCtrl.dismiss(null, "cancel");
  }
}