<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import Button from 'primevue/button';
import { Form } from '@primevue/forms';
import InputText from 'primevue/inputtext';
import Message from 'primevue/message';
import Toast from 'primevue/toast';

import { useUserStore } from "@/stores/userStore";

const userStore = useUserStore();
const username = ref();
const password = ref();
const router = useRouter();
const route = useRoute();
const next = route.query.next;


function handleLogin({ valid }) {
  if (!valid) {
    return;
  }
  userStore.login(username.value, username.value).then((data) => {
    router.push(next);
  });
}

const initialValues = reactive({
  username: 'joe',
  password: 'password',
});
const resolver = ({ values }) => {
  const errors = {};
  if (!values.username) {
    errors.username = [{message: 'Username is required.'}];
  }
  username.value = values.username;
  if (!values.password) {
    errors.password = [{message: 'Password is required.'}];
  }
  password.value = values.password;
  return { errors }
};

</script>

<template>
  <div class="login-form">
    <Toast/>
    <Form :initialValues :resolver @submit="handleLogin" v-slot="$form">
      <div>
        <label for="username">Username</label>
        <InputText name="username" v-model="username" id="username" type="text" />
        <Message v-if="$form.username?.invalid" severity="error" size="small" variant="simple">
          {{ $form.username.error?.message }}
        </Message>
      </div>
      <div>
        <label for="password">Password</label>
        <InputText name="password" v-model="password" id="password" type="password" />
        <Message v-if="$form.password?.invalid" severity="error" size="small" variant="simple">
          {{ $form.password.error?.message }}
        </Message>
      </div>
      <div>
        <label>&nbsp;</label>
        <Button type="submit">Login</Button>
      </div>
    </Form>
  </div>
</template>

<style lang="scss" scoped>
.login-form {
  display: flex;
  justify-content: center;
  form {
    display: flex;
    flex-direction: column;
    font-size: 120%;
    margin: 20px;
    gap: 10px;
    > div {
      padding: 4px;
      display: flex;
      flex-direction: column;
    }
  }
}
</style>
