<template>
  <div class="grow flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8 pb-20">
      <div class="flex flex-col items-center gap-4">
        <img src="/Logo.png" alt="LOGO" class="h-36" />
        <h2 class="text-center text-4xl font-extrabold text-gray-900">Einrichtung</h2>
      </div>

      <form class="flex flex-col gap-2" @submit.prevent="setup">
        <div class="-space-y-px">
          <div>
            <input id="username" name="username" type="text" required placeholder="Benutzer" class="!rounded-b-none" />
          </div>
          <div>
            <input id="mail" name="mail" type="email" required placeholder="Mailadresse" class="!rounded-none" />
          </div>
          <div>
            <input id="firstname" name="firstname" type="text" required placeholder="Vorname" class="!rounded-none" />
          </div>
          <div>
            <input id="lastname" name="lastname" type="text" required placeholder="Nachname" class="!rounded-t-none" />
          </div>
        </div>

        <div class="flex flex-row gap-2">
          <button type="submit" primary :disabled="setupStatus == 'loading' || setupStatus == 'success'">
            Admin-Account anlegen
          </button>
          <Spinner v-if="setupStatus == 'loading'" class="my-auto" />
          <SuccessCheckmark v-else-if="setupStatus == 'success'" />
          <FailureXMark v-else-if="setupStatus == 'failed'" />
        </div>
        <p v-if="setupMessage" class="text-center">{{ setupMessage }}</p>
      </form>

      <FormBottomBar />
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent } from "vue";
import Spinner from "@/components/Spinner.vue";
import SuccessCheckmark from "@/components/SuccessCheckmark.vue";
import FailureXMark from "@/components/FailureXMark.vue";
import FormBottomBar from "@/components/FormBottomBar.vue";
</script>

<script lang="ts">
export default defineComponent({
  data() {
    return {
      setupStatus: undefined as undefined | "loading" | "success" | "failed",
      setupMessage: "" as string,
    };
  },
  methods: {
    setup(e: any) {
      let formData = e.target.elements;
      this.setupStatus = "loading";
      this.setupMessage = "";
      this.$http
        .post(`/setup`, {
          username: formData.username.value,
          mail: formData.mail.value,
          firstname: formData.firstname.value,
          lastname: formData.lastname.value,
        })
        .then((result) => {
          this.setupStatus = "success";
          this.setupMessage = "Sie haben einen Verifizierungslink per Mail erhalten.";
        })
        .catch((err) => {
          this.setupStatus = "failed";
          this.setupMessage = err.response.data;
        });
    },
  },
});
</script>
