<template>
  <LoginModal v-if="modal_visible" @submit="on_submit" @cancel="on_cancel" />

  <BulmaButton
    v-bind="$attrs"
    :icon="['fas', store.is_admin ? 'fa-toggle-on' : 'fa-toggle-off']"
    :busy="is_busy"
    text="Admin"
    @click.left="on_click"
  />
</template>

<script setup lang="ts">
import { APIError } from "@/lib/api_error";
import { Credentials } from "@/lib/model";
import { advent22Store } from "@/lib/store";
import { ref } from "vue";

import BulmaButton from "./bulma/Button.vue";
import LoginModal from "./LoginModal.vue";

const modal_visible = ref(false);
const is_busy = ref(false);
const store = advent22Store();

function on_click(): void {
  if (store.is_admin) {
    store.logout();
  } else {
    // show login modal
    is_busy.value = true;
    modal_visible.value = true;
  }
}

async function on_submit(creds: Credentials): Promise<void> {
  modal_visible.value = false;

  store
    .login(creds)
    .catch((error) => APIError.alert(error))
    .finally(() => (is_busy.value = false));
}

function on_cancel(): void {
  modal_visible.value = false;
  is_busy.value = false;
}
</script>
