<template>
  <div class="w-full h-full text-primary flex pt-20 items-center flex-col">
    <h1 class="sm:text-4xl text-2xl font-bold text-center mb-10">Whitelist</h1>
    <div v-if="!user.minecraft.uuid" class="flex flex-col items-center">
      <p class="max-w-xl mb-10 sm:text-base text-sm">
        Je bent momenteel niet gewhitelist. Om toegang te krijgen tot de Minecraft server moet je in Minecraft naar de server met het ip <span class="highlight">play.polarcraft.xeovalyte.com</span> gaan. Vervolgens krijg je een code te zien, vul deze code hieronder in.
      </p>
      <div class="flex gap-2">
        <Input v-model:value="code">Code</Input>
        <Button @click="submitCode">Submit</Button>
      </div>
    </div>
    <div v-else class="flex justify-center gap-4 flex-wrap max-w-3xl w-full">
      <img :src="'https://api.mineatar.io/face/' + user.minecraft.uuid + '?scale=16'" class="w-24 rounded shadow">
      <div class="rounded flex border-2 border-primary p-4 w-full max-w-md">
        <ul class="my-auto">
          <li>Username: <b>{{ user.minecraft.username }}</b></li>
          <li>UUID: <b>{{ user.minecraft.uuid }}</b></li>
        </ul>
      </div>
      <div class="w-full flex justify-center gap-4 mt-2">
        <Button type="danger" @click="removeWhitelist">
          Remove from whitelist
        </Button>
        <Button @click="refreshUsername">
          Refresh Username
        </Button>
      </div>
    </div>
  </div>
</template>

<script setup>
definePageMeta({
  middleware: ["auth"]
})

const user = useState('user')
const code = ref('')

const refreshUsername = async () => {
  try {
    const response = await $fetch('/api/minecraft/refreshusername')

    user.value.minecraft.username = response.username

    useToast().success('Username is ververst')
  } catch (e) {
    console.log(e)

    useToast().error(e.statusMessage)
  }
}

const removeWhitelist = async () => {
  try {
    await $fetch('/api/minecraft/removewhitelist')

    user.value.minecraft.uuid = null
    user.value.minecraft.username = null

    useToast().success('Minecraft is niet meer gekoppeld')
  } catch (e) {
    console.log(e)
    useToast().error(e.statusMessage)
  }
}

const submitCode = async () => {
  try {
    const response = await $fetch('/api/minecraft/whitelist', {
      method: 'POST',
      body: {
        code: code.value
      }
    })

    user.value.minecraft.uuid = response.uuid
    user.value.minecraft.username = response.username

    useToast().success('Successfully whitelisted')
  } catch (e) {
    console.log(e);
    useToast().error(e.statusMessage)
  }
}
</script>
