<script setup lang="ts">
import { useUserInfo } from "@/composables/useUserInfo.ts";
import { useRouter } from 'vue-router';
import {useQuasar} from "quasar";
import axios from "axios";

const api = window?.__RUNTIME_CONFIG__?.API_URL;
const $q = useQuasar()
let userinfo = useUserInfo();
const router = useRouter();

const handleLogoff = () => {

  axios.post(`${api}/logout`, {}, {withCredentials: true}).then((response) => {
    const responseData = response.data
    console.log("Response" + responseData.status)
    $q.notify({
      message: `You successfully logged out!`,
      color: 'green-6',
      icon: 'check_circle',
      position: 'top'
    });
    router.push({ name: 'login' });
  }).catch((err) => {
    console.log("ERROR:" + err)
    $q.notify({
      message: `Something went wrong`,
      color: 'red-6',
      icon: 'cancel',
      position: 'top'
    });
  })

}
</script>

<template>
  <div class="row items-center q-gutter-x-md">

    <div
      v-if="userinfo.username"
      class="text-body1 text-weight-medium row items-center q-gutter-x-sm cursor-pointer relative-position"
    >
      <div id="user-menu-target" class="row items-center q-gutter-x-sm" style="min-width: 150px">
        <q-icon name="account_circle" size="md" />
        <span>{{ userinfo.username }}</span>
        <q-icon name="arrow_drop_down" size="sm" />
      </div>

      <q-menu
        target="#user-menu-target"
        anchor="bottom right"
        self="top right"
      >
        <q-list style="max-width: 150px" class="bg-dark">
          <q-item
            clickable
            v-close-popup
            @click="handleLogoff"
            class="text-negative"
          >
            <q-item-section avatar>
              <q-icon name="logout" color="negative" />
            </q-item-section>
            <q-item-section>Log Off</q-item-section>
          </q-item>
        </q-list>
      </q-menu>
    </div>

    <div v-else class="text-caption text-grey-4">
      Not Logged In
    </div>

  </div>
</template>
<style scoped>
#user-menu-target:hover {
  opacity: 0.8;
}
</style>
