<template>
  <form @submit.prevent="save()">
    <PrimeFloatLabel variant="on">
      <PrimeInputText id="displayName" v-model="displayName" fluid autocomplete="off" />
      <label for="displayName">Display name</label>
    </PrimeFloatLabel>

    <PrimeDivider />

    <div class="flex items-center gap-3">
      <PrimeButton label="Save" :disabled="!valid" :loading="saving" fluid type="submit" />
      <PrimeButton severity="danger" class="shrink-0" @click="logout()">
        <template #icon>
          <LogOut />
        </template>
      </PrimeButton>
    </div>
  </form>
</template>

<script setup lang="ts">
import { LogOut } from 'lucide-vue-next'

definePageMeta({
  name: 'Profile',
})

const { me, setMe, logout } = useAuth()
const signaling = useSignaling()
const toast = useToast()

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

const saving = ref(false)

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

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

  return true
})

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

  saving.value = true

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

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

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

  saving.value = false
}
</script>
