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

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

async function handleSave() {
  if (!usernamePattern.test(username.value)) {
    const toast = await toastController.create({
      message: "用户名格式不正确",
      duration: 2000,
      position: "bottom",
      color: "danger",
    });
    await toast.present();
    return;
  }
  const { data } = await safeClient(authClient.updateUser({
    username: username.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="username"
          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>
