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

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

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

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

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