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

const { t } = useI18n();
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: t("userSettings.nickname.invalidFormat"),
      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: t("userSettings.nickname.updateSuccess"),
      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>{{ t('userSettings.nickname.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="t('userSettings.nickname.placeholder')"
          class="w-full"
        />

        <div class="text-xs text-gray-500">
          {{ t('userSettings.nickname.hint') }}
        </div>

        <ion-button expand="block" class="mt-5" @click="handleSave">
          {{ t('userSettings.nickname.save') }}
        </ion-button>
      </div>
    </ion-content>
  </ion-page>
</template>

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