<template>
  <div>
    <div class="mb-10 flex">
      <UAvatarGroup size="xl" class="mr-5">
        <UAvatar :src="discordAvatarUrl" alt="Discord Avatar" placeholder="DC" />
        <UAvatar v-if="minecraftAvatarUrl" :src="minecraftAvatarUrl" alt="Minecraft Avatar" placeholder="MC" />
      </UAvatarGroup>
      <h2>
        <span class="text-xl">
          Welkom, <b>{{ user.username }}</b>
        </span>
        <p class="text-gray-400">
          Happy to see you again
        </p>
      </h2>
    </div>
    <div class="grid w-full grid-cols-12 gap-6">
      <div class="col-span-6 rounded-lg border border-gray-700 bg-gray-800 p-5">
        <div class="mb-5 flex items-center">
          <UAvatar size="2xl" :src="discordAvatarUrl" class="mr-6 aspect-square" />
          <div>
            <h3 class="mb-2 text-xl font-bold">
              Discord
              <span v-if="user.usernameType === 'discord'" class="text-base font-normal text-gray-400">
                Default
              </span>
            </h3>
            <ul>
              <li>Username: {{ user.discord.username }}</li>
              <li>ID: {{ user.discord.id }}</li>
            </ul>
          </div>
        </div>
        <div class="space-x-3">
          <UButton v-if="user.usernameType === 'minecraft'" :disabled="disableButtons" @click="setDefaultUsername('discord')">
            Set Default
          </UButton>
          <UButton variant="soft" :disabled="disableButtons" @click="refreshDiscordData">
            Refresh Data
          </UButton>
        </div>
      </div>
      <div v-if="user.minecraft" class="col-span-6 rounded-lg border border-gray-700 bg-gray-800 p-5">
        <div class="mb-5 flex items-center">
          <UAvatar size="2xl" :src="minecraftAvatarUrl" class="mr-6 aspect-square" />
          <div>
            <h3 class="mb-2 text-xl font-bold">
              Minecraft
              <span v-if="user.usernameType === 'minecraft'" class="text-base font-normal text-gray-400">
                Default
              </span>
            </h3>
            <ul>
              <li>Username: {{ user.minecraft.username }}</li>
              <li>UUID: {{ user.minecraft.uuid }}</li>
            </ul>
          </div>
        </div>
        <div class="space-x-3">
          <UButton v-if="user.usernameType === 'discord'" :disabled="disableButtons" @click="setDefaultUsername('minecraft')">
            Set Default
          </UButton>
          <UButton variant="soft" :disabled="disableButtons" @click="refreshMinecraftData">
            Refresh Data
          </UButton>
          <UButton color="red" variant="outline" :disabled="disableButtons" @click="disconnectMinecraft">
            Disconnect
          </UButton>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
definePageMeta({
  middleware: ['auth'],
  title: 'Dashboard | Polarcraft'
})

const user = useState<IUser>('user')
const disableButtons = ref(false)

const discordAvatarUrl = computed(() => {
  return 'https://cdn.discordapp.com/avatars/' + user.value.discord.id + '/' + user.value.discord.avatarHash + '.png'
})

const minecraftAvatarUrl = computed(() => {
  if (!user.value.minecraft) {
    return ''
  }
  return 'https://api.mineatar.io/face/' + user.value.minecraft.uuid + '?scale=16'
})

const disconnectMinecraft = async () => {
  disableButtons.value = true

  try {
    await $fetch('/api/users/@me/minecraft', {
      method: 'DELETE'
    })

    delete user.value.minecraft

    useToast().add({ title: 'Successfully disconnected Minecraft', color: 'green' })
  } catch (e: any) {
    console.error(e)

    useToast().add({ title: e.statusMessage, color: 'red' })
  }

  disableButtons.value = false
}

const refreshMinecraftData = async () => {
  disableButtons.value = true

  try {
    const response = await $fetch('/api/users/@me/minecraft')

    user.value.minecraft = response

    useToast().add({ title: 'Successfully refreshed Minecraft data', color: 'green' })
  } catch (e: any) {
    console.error(e)

    useToast().add({ title: e.statusMessage, color: 'red' })
  }

  disableButtons.value = false
}

const refreshDiscordData = async () => {
  disableButtons.value = true

  try {
    const response: any = await $fetch('/api/users/@me/discord')

    user.value.discord = response

    useToast().add({ title: 'Successfully refreshed Discord data', color: 'green' })
  } catch (e: any) {
    console.error(e)

    useToast().add({ title: e.statusMessage, color: 'red' })
  }

  disableButtons.value = false
}

const setDefaultUsername = async (usernameType: string) => {
  disableButtons.value = true

  try {
    const response = await $fetch('/api/users/@me/username', {
      method: 'PUT',
      body: {
        usernameType
      }
    })

    user.value.usernameType = usernameType
    user.value.username = response

    useToast().add({ title: 'Successfully updated username', color: 'green' })
  } catch (e: any) {
    console.error(e)

    useToast().add({ title: e.statusMessage, color: 'red' })
  }

  disableButtons.value = false
}
</script>
