<template>
  <div>
    <AppHeader title="Preferences" secondary />

    <form class="flex flex-col gap-3 p-3" @submit.prevent="save">
      <PrimeFloatLabel variant="on">
        <PrimeInputText id="username" v-model="displayName" size="large" fluid autocomplete="off" />
        <label for="username">Username</label>
      </PrimeFloatLabel>

      <PrimeButton label="Save" type="submit" :disabled="!valid" />
    </form>

    <div class="p-3">
      <PrimeButton label="Logout" fluid severity="danger" @click="logout" />
    </div>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  name: 'Preferences',
})

const { me, setMe, logout } = useAuth()

const signaling = useSignaling()
const toast = useToast()

const displayName = ref(me.value?.displayName || '')

const valid = computed(() => {
  if (!displayName.value || !me.value)
    return false

  if (displayName.value === me.value.displayName)
    return false

  return true
})

async function save() {
  if (!valid.value)
    return

  const updatedMe = await signaling.socket.value?.emitWithAck('updateClient', {
    displayName: displayName.value,
  })

  setMe({ ...me.value, displayName: updatedMe.displayName })

  toast.add({ severity: 'success', summary: 'Saved', life: 1000, closable: false })
}
</script>
