<script lang='ts' setup>
import { toastController } from "@ionic/vue";
import { client, safeClient } from "@/api";

const userStore = useUserStore();
const { userProfile } = storeToRefs(userStore);
const nickname = ref(userProfile.value?.nickname || "");
const { updateProfile } = useUserStore();

async function handleSave() {
  if (!usernamePattern.test(nickname.value)) {
    const toast = await toastController.create({
      message: "昵称格式不正确",
      duration: 2000,
      position: "bottom",
      color: "danger",
    });
    await toast.present();
    return;
  }
  const { data } = await safeClient(client.api.user.profile.put({
    nickname: nickname.value,
  }));
  if (data) {
    updateProfile();
    const toast = await toastController.create({
      message: "昵称更新成功",
      duration: 2000,
      position: "bottom",
      color: "success",
    });
    await toast.present();
  }
}
</script>

<template>
  <ion-page>
    <ion-header>
      <ion-toolbar class="ion-toolbar">
        <ui-back-button slot="start" />
        <ion-title>昵称设置</ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true" class="ion-padding">
      <div class="space-y-3">
        <ui-input
          v-model="nickname"
          placeholder="请输入昵称"
          class="w-full"
        />

        <div class="text-xs text-gray-500">
          仅支持字母、数字、下划线，长度 3-20 个字符
        </div>

        <ion-button expand="block" class="mt-5" @click="handleSave">
          保存
        </ion-button>
      </div>
    </ion-content>
  </ion-page>
</template>

<style lang='css' scoped></style>
