<template>
  <div class="modal is-active">
    <div class="modal-background" />

    <div class="modal-card">
      <header class="modal-card-head">
        <p class="modal-card-title">Login</p>
        <button class="delete" @click.left="cancel" />
      </header>

      <section class="modal-card-body">
        <div class="field">
          <label class="label">Username</label>
          <div class="control">
            <input
              ref="username_input"
              class="input"
              type="text"
              v-model="creds.username"
            />
          </div>
        </div>

        <div class="field">
          <label class="label">Passwort</label>
          <div class="control">
            <input class="input" type="password" v-model="creds.password" />
          </div>
        </div>
      </section>

      <footer class="modal-card-foot is-flex is-justify-content-space-around">
        <BulmaButton
          class="is-success"
          @click.left="submit"
          :icon="['fas', 'fa-unlock']"
          text="Login"
        />
        <BulmaButton
          class="is-danger"
          @click.left="cancel"
          :icon="['fas', 'fa-circle-xmark']"
          text="Abbrechen"
        />
      </footer>
    </div>
  </div>
</template>

<script setup lang="ts">
import { wait_for } from "@/lib/helpers";
import type { Credentials } from "@/lib/model";
import { onBeforeUnmount, onMounted, ref, useTemplateRef } from "vue";
import BulmaButton from "./bulma/Button.vue";

const username_input = useTemplateRef("username_input");

const emit = defineEmits<{
  (event: "submit", creds: Credentials): void;
  (event: "cancel"): void;
}>();

const creds = ref<Credentials>({
  username: "",
  password: "",
});

function submit(): void {
  emit("submit", creds.value);
}

function cancel(): void {
  emit("cancel");
}

onMounted(() => {
  const on_keydown = (e: KeyboardEvent) => {
    if (e.key === "Enter") submit();
    else if (e.key === "Escape") cancel();
  };

  window.addEventListener("keydown", on_keydown);

  wait_for(
    () => username_input.value !== null,
    () => username_input.value!.focus(),
  );

  onBeforeUnmount(() => {
    window.removeEventListener("keydown", on_keydown);
  });
});
</script>
