<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: 'login' }" class="font-semibold text-primary"
        >Логин</RouterLink
      >
    </p>
    <VaInput
      v-model="formData.email"
      :rules="[
        (v) => !!v || 'Email обязателен',
        (v) => /.+@.+\..+/.test(v) || 'Email должен быть валидным',
      ]"
      class="mb-4"
      label="Email"
      type="email"
    />
    <VaValue v-slot="isPasswordVisible" :default-value="false">
      <VaInput
        ref="password1"
        v-model="formData.password"
        :rules="passwordRules"
        :type="isPasswordVisible.value ? 'text' : 'password'"
        class="mb-4"
        label="Пароль"
        messages="Пароль должен быть длинее 4-х символов."
        @clickAppendInner.stop="
          isPasswordVisible.value = !isPasswordVisible.value
        "
      >
        <template #appendInner>
          <VaIcon
            :name="
              isPasswordVisible.value ? 'mso-visibility_off' : 'mso-visibility'
            "
            class="cursor-pointer"
            color="secondary"
          />
        </template>
      </VaInput>
      <VaInput
        ref="password2"
        v-model="formData.repeatPassword"
        :rules="[
          (v) => !!v || 'Поле повторите пароль обязательное',
          (v) => v === formData.password || 'Пароли не совпадают',
        ]"
        :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="flex justify-center mt-4">
      <VaButton class="w-full" @click="submit"> Создать аккуант</VaButton>
    </div>
  </VaForm>
</template>

<script lang="ts" setup>
import axios from "axios";
import { reactive } from "vue";
import { useRouter } from "vue-router";
import { useForm, useToast } from "vuestic-ui";

const { validate } = useForm("form");
const { push } = useRouter();
const { init } = useToast();

const formData = reactive({
  email: "",
  password: "",
  repeatPassword: "",
});

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

const submit = () => {
  if (validate()) {
    axios
      .post(`/api/v0/signup`, {
        email: 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) => {});
      });
  }
};

const passwordRules: ((v: string) => boolean | string)[] = [
  (v) => !!v || "Поле пароль обязательное",
  (v) => (v && v.length >= 5) || "Пароль должен быть длинее 5-ти символов",
];
</script>
