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

    <div class="modal-card">
      <form @submit.prevent="submit">
        <header class="modal-card-head">
          <p class="modal-card-title">Login</p>
          <button
            class="delete"
            aria-label="close"
            @click.left="set_active(false)"
          />
        </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="username"
              />
            </div>
          </div>

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

      <footer class="modal-card-foot is-flex is-justify-content-space-around">
        <BulmaButton
          class="button is-success"
          @click.left="submit"
          icon="fa-solid fa-unlock"
          text="Login"
        />
        <BulmaButton
          class="button is-danger"
          @click.left="set_active(false)"
          icon="fa-solid fa-circle-xmark"
          text="Abbrechen"
        />
      </footer>
    </div>
  </div>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";

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

@Options({
  components: {
    BulmaButton,
  },
  emits: ["submit"],
})
export default class extends Vue {
  public active = false;
  public username = "";
  public password = "";

  declare $refs: {
    username_input: HTMLInputElement | null | undefined;
  };

  public created() {
    window.addEventListener("keydown", (e) => {
      if (e.key == "Escape") this.set_active(false);
    });
  }

  public set_active(state: boolean) {
    this.active = state;

    if (this.active) {
      this.username = "";
      this.password = "";

      this.$nextTick(() => {
        if (this.$refs.username_input instanceof HTMLInputElement) {
          this.$refs.username_input?.focus();
        }
      });
    }
  }

  public submit() {
    this.$advent22.set_api_auth(this.username, this.password);
    this.$emit("submit");
    this.set_active(false);
  }
}
</script>
