<script setup>
import {ref} from 'vue'
import {useRoute} from 'vue-router';
import Loader from '@/components/Loader.vue';
import router from '@/router'
import {useErrorStore} from '@/stores/errors'


const errorStore = useErrorStore()

const apiHost = import.meta.env.VITE_CONJUREOS_HOST
const isLoginIn = ref(false)

const route = useRoute();

if (!route.query.token || !route.query.action) {
  router.push("/close")
}

const submit = (form) => {
  const formData = new FormData(form)
  formData.set('token', route.query.token.toString())
  isLoginIn.value = true
  const myHeaders = new Headers();
  myHeaders.append("API-Version", 1);
  fetch(apiHost + route.query.action, {
    method: 'POST',
    body: formData,
    headers: myHeaders,
  })
      .then((response) => {
        isLoginIn.value = false
        if (response.status !== 200)
          return response.text().then(error => {
                throw new Error(error)
              }
          )
        return response.text()
      })
      .then((result) => {
        router.push('/close')
      })
      .catch((error) => {
        isLoginIn.value = false
        errorStore.unshift(error)
      })
}
</script>

<template>
  <form ref="loginForm" enctype="multipart/form-data" @submit.prevent="submit($refs.loginForm)">
    <label for="username">username</label>
    <input
        required
        type="text"
        class="border border-primary rounded-lg px-3 py-2 bg-transparent focus:outline-none focus:border-accent"
        name="username"
        id="username"
    />
    <label for="password">password</label>
    <input
        required
        type="password"
        class="border border-primary rounded-lg px-3 py-2 bg-transparent focus:outline-none focus:border-accent"
        name="password"
        id="password"
    />
    <button
        v-if="!isLoginIn"
        class="bg-transparent text-primary font-semibold hover:text-white py-2 px-4 border border-gray-500 hover:border-transparent rounded"
        type="submit"
    >
      Login
    </button>
    <span class="loader" v-else>
        <Loader :variant="2"/>
    </span>
  </form>
</template>

<style scoped>
header {
  line-height: 1.5;
}

form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.logo {
  user-drag: none;
  -webkit-user-drag: none;
  display: block;
  margin: 0 auto 2rem;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }
}
</style>
