<template>
  <form @submit.prevent="save()">
    <PrimeDivider align="left">
      General
    </PrimeDivider>

    <PrimeFloatLabel variant="on">
      <PrimeInputText id="displayName" v-model="displayName" fluid autocomplete="off" />
      <label for="displayName">Display name</label>
    </PrimeFloatLabel>

    <div class="flex items-center gap-3 mt-6">
      <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 chadApi from '#shared/chad-api'
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 chadApi('/profile', {
    method: 'PATCH',
    body: {
      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>
