<script setup lang="ts">
import { Form, Field } from 'vee-validate';
import * as Yup from 'yup';
import { axiosInstance } from '@/main'
import { router } from '@/router/router'
import { useUserStore } from '@/stores/user.store'
import { getActivePinia, storeToRefs } from 'pinia'
import { useCategoriesStore } from '@/stores/categories.store'
import { useSiteControlStore } from '@/stores/siteControl.store'

const schema = Yup.object().shape({
  username: Yup.string().required('Nazwa użytkownika jest wymagana'),
  password: Yup.string().required('Hasło jest wymagane')
});

async function onSubmit(values : any, { setErrors } : any) {
  const { username, password } = values;

  const body = await axiosInstance.post('/login', {
    username: username,
    password: password
  }).catch ((error) => {
    if(error.response.status == 401) {
      setErrors({ apiError: "unauthorized" })
    }
  });
  if(body != undefined && body.status == 200) {
    const userStore = useUserStore();
    const siteControlStore = useSiteControlStore();
    const { username } = storeToRefs(userStore);
    username.value = body.data.displayName;
    await siteControlStore.newOrder(true);
  }

}
</script>

<template>
  <div class="container is-flex is-justify-content-space-evenly is-align-items-center" style="min-height: calc(100vh - 3.5rem)">
    <div class="box" style="width: 75%">
      <h1 class="title is-3 mb-3">Login</h1>
      <Form @submit="onSubmit" :validation-schema="schema" v-slot="{ errors, isSubmitting }">
        <div class="form-group">
          <div class="field mb-3">
            <label class="label is-small">Nazwa użytkownika</label>
            <div class="field is-small mb-3">
              <Field class="input is-small"
                     type="text"
                    name="username"
                     :class="{ 'is-danger': errors.username }"/>
            </div>
          </div>
          <div class="has-text-danger">{{errors.username}}</div>
        </div>
        <div class="form-group">
          <div class="field mb-3">
            <label class="label is-small">Hasło</label>
            <div class="field is-small mb-3">
              <Field class="input is-small"
                     type="password"
                     name="password"
                     :class="{ 'is-danger': errors.password }"/>
            </div>
          </div>
          <div class="has-text-danger">{{errors.password}}</div>
        </div>
        <div class="form-group">
          <button class="button is-info" :disabled="isSubmitting">
            <span v-show="isSubmitting" class="spinner-border spinner-border-sm mr-1"></span>
            Login
          </button>
        </div>
        <div v-if="errors.apiError" class="has-text-danger mt-3 mb-3">Hasło lub nazwa użytkownika jest niepoprawna.</div>
      </Form>
    </div>

  </div>
</template>
