<template>
  <div class="q-pa-md flex flex-center">
    <q-card
      class="q-pa-lg shadow-3"
      style="width: 400px; max-width: 90vw; border-radius: 16px;"
    >
      <q-card-section class="text-center">
        <div class="text-h6 q-mt-md">Enter Username</div>
      </q-card-section>

      <q-card-section>
        <q-input
          v-model="user.username"
          filled
          label="Username"
          maxlength="32"
          counter
          dense
          style="border-radius: 6px;"
        >
          <template #prepend>
            <q-icon name="account_circle" />
          </template>
        </q-input>
      </q-card-section>

      <q-card-actions align="center">
        <q-btn
          label="Go!"
          color="primary"
          @click="setUsername"
          rounded
          unelevated
          size="lg"
          class="full-width"
        />
      </q-card-actions>
    </q-card>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useQuasar, LocalStorage } from "quasar";
import { api } from 'src/boot/axios';
import { useRouter } from 'vue-router'

const router = useRouter()
const $q = useQuasar();
const user = ref({ username:"", id:0 });

async function setUsername() {
    if (!user.value.username) {
        $q.notify({
            type: "negative",
            message: "Please enter a username!",
        });
        return;
    }

    api.post("/api/users", {
      username: user.value.username
    })
    
    .then(function (response) {
      console.log(response);

      user.value.username = response.data.username
      user.value.id = response.data.id

      LocalStorage.setItem("user", user.value);

      $q.notify({
        type: "positive",
        message: "Success!",
      });

      router.push("/")
    })
    
    .catch(function (error) {
      console.log(error);

      $q.notify({
        type: "negative",
        message: error.response.data.error,
      });
    });
}
</script>
