<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 v-if="isTauri" class="p-3">
      <PrimeButton label="Check for Updates" fluid severity="info" @click="onCheckForUpdates" />
    </div>

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

  <PrimeToast position="bottom-center" group="updater">
    <template #container="slotProps">
      <div class="p-3">
        <div class="font-medium text-lg mb-4">
          {{ slotProps.message.detail }}
        </div>
        <div class="flex gap-3">
          <PrimeButton size="small" label="Update now" @click="() => {}" />
          <PrimeButton size="small" label="Later" severity="secondary" outlined @click="slotProps.closeCallback()" />
        </div>
      </div>
    </template>
  </PrimeToast>
</template>

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

const { isTauri } = useApp()
const { checkForUpdates } = useUpdater()
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 onCheckForUpdates() {
  const update = await checkForUpdates()

  toast.removeGroup('updater')

  if (!update) {
    toast.add({ severity: 'success', summary: 'You are up to date', closable: false, life: 1000 })

    return
  }

  toast.add({
    group: 'updater',
    severity: 'info',
    detail: `Version ${update?.version ?? '1.0.1'} is available!`,
    closable: false,
  })

  // asdasd
}

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>
