<template>
  <VaForm ref="form" @submit.prevent="submit" @keyup.enter="submit">
    <h1 class="font-semibold text-4xl mb-4">Войти</h1>
    <p class="text-base mb-4 leading-5">
      Впервые здесь?
      <RouterLink :to="{ name: 'signup' }" class="font-semibold text-primary"
        >Регистрация</RouterLink
      >
    </p>
    <VaInput
      v-model="formData.email"
      :rules="[validators.required, validators.email]"
      class="mb-4"
      label="Email"
      type="email"
    />
    <VaValue v-slot="isPasswordVisible" :default-value="false">
      <VaInput
        v-model="formData.password"
        :rules="[validators.required]"
        :type="isPasswordVisible.value ? 'text' : 'password'"
        class="mb-4"
        label="Пароль"
        @clickAppendInner.stop="
          isPasswordVisible.value = !isPasswordVisible.value
        "
      >
        <template #appendInner>
          <VaIcon
            :name="
              isPasswordVisible.value ? 'mso-visibility_off' : 'mso-visibility'
            "
            class="cursor-pointer"
            color="secondary"
          />
        </template>
      </VaInput>
    </VaValue>

    <div
      class="auth-layout__options flex flex-col sm:flex-row items-start sm:items-center justify-between"
    >
      <RouterLink
        :to="{ name: 'recover-password' }"
        class="mt-2 sm:mt-0 sm:ml-1 font-semibold text-primary"
      >
        Забыли пароль?
      </RouterLink>
    </div>

    <div class="flex justify-center mt-4">
      <VaButton class="w-full" @click="submit"> Вход</VaButton>
    </div>
  </VaForm>
</template>

<script lang="ts" setup>
import { inject } from 'vue'

import axios from "axios";
import { reactive } from "vue";
import { useRouter } from "vue-router";
import { useForm, useToast } from "vuestic-ui";
import { validators } from "../../services/utils";

const { validate } = useForm("form");
const { push } = useRouter();
const { init } = useToast();
const HOST = inject('HOST');
const formData = reactive({
  email: "",
  password: "",
  keepLoggedIn: false,
});

const token = localStorage.getItem("token");
if (token != undefined && token.length > 0) {
        push({ name: "dashboard" }).catch((error) => {});
}

const submit = () => {
  if (validate()) {
    axios
      .post(`/api/v0/signin`, {
        login: formData.email,
        password: formData.password,
      })
      .then((response) => {
        localStorage.setItem('token', response.data.token);
        localStorage.setItem('profile', JSON.stringify(response.data.profile));
        localStorage.setItem('user', JSON.stringify(response.data.user));
        localStorage.setItem('attachments', JSON.stringify(response.data.attachments));
        
        init({ message: "Вы успешно вошли!", color: "success" });
        push({ name: "dashboard" });
      })
      .catch((error) => {
        
          init({
            message: "Неверный логин или пароль",
            color: "error",
          });

      });
  }
};
</script>
