<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">{{config.app_name_overwrite ?? "FF Admin"}}</h2>
      </div>

      <form class="flex flex-col gap-2" @submit.prevent="login">
        <div class="-space-y-px">
          <div>
            <input id="username" name="username" type="text" required placeholder="Benutzer" class="!rounded-b-none" />
          </div>
          <div>
            <input
              id="totp"
              name="totp"
              type="text"
              required
              placeholder="TOTP"
              class="!rounded-t-none"
              autocomplete="off"
            />
          </div>
        </div>
        <RouterLink :to="{ name: 'reset-start' }" class="w-fit self-end text-primary">TOTP verloren</RouterLink>

        <div class="flex flex-row gap-2">
          <button type="submit" primary :disabled="loginStatus == 'loading' || loginStatus == 'success'">
            anmelden
          </button>
          <Spinner v-if="loginStatus == 'loading'" class="my-auto" />
          <SuccessCheckmark v-else-if="loginStatus == 'success'" />
          <FailureXMark v-else-if="loginStatus == 'failed'" />
        </div>
        <p v-if="loginError" class="text-center">{{ loginError }}</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 { resetAllPiniaStores } from "@/helpers/piniaReset";
import FormBottomBar from "@/components/FormBottomBar.vue";
import { config } from "@/config"
</script>

<script lang="ts">
export default defineComponent({
  data() {
    return {
      loginStatus: undefined as undefined | "loading" | "success" | "failed",
      loginError: "" as string,
    };
  },
  mounted() {
    resetAllPiniaStores();
  },
  methods: {
    login(e: any) {
      let formData = e.target.elements;
      this.loginStatus = "loading";
      this.loginError = "";
      this.$http
        .post(`/auth/login`, {
          username: formData.username.value,
          totp: formData.totp.value,
        })
        .then((result) => {
          this.loginStatus = "success";
          localStorage.setItem("accessToken", result.data.accessToken);
          localStorage.setItem("refreshToken", result.data.refreshToken);
          setTimeout(() => {
            this.$router.push(`/admin`);
          }, 1000);
        })
        .catch((err) => {
          this.loginStatus = "failed";
          this.loginError = err.response.data;
        });
    },
  },
});
</script>
