<template>
  <VaModal
    max-width="530px"
    :mobile-fullscreen="false"
    hide-default-actions
    model-value
    close-button
    @update:modelValue="emits('cancel')"
  >
    <h1 class="va-h5 mb-4">Сброс пароля</h1>
    <VaForm ref="form" class="space-y-6" @submit.prevent="submit">
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <VaInput
          v-model="newPassword"
          :rules="newPasswordRules"
          label="Новый пароль"
          placeholder="Новый пароль"
          required-mark
          type="password"
        />
        <VaInput
          v-model="repeatNewPassword"
          :rules="repeatNewPasswordRules"
          label="Повторите новый пароль"
          placeholder="Повторите новый пароль"
          required-mark
          type="password"
        />
      </div>
      
      <div
        class="flex flex-col-reverse md:justify-end md:flex-row md:space-x-4"
      >
        <VaButton
          :style="buttonStyles"
          preset="secondary"
          color="secondary"
          @click="emits('cancel')"
        >
          Cancel</VaButton
        >
        <VaButton
          :style="buttonStyles"
          class="mb-4 md:mb-0"
          type="submit"
          @click="submit"
        >
          Обновить пароль</VaButton
        >
      </div>
    </VaForm>
  </VaModal>
</template>
<script lang="ts" setup>
import axios from "axios";
import { inject } from 'vue'
import { ref } from "vue";
import { useForm, useToast } from "vuestic-ui";

import { buttonStyles } from "../styles";

const newPassword = ref<string>();
const repeatNewPassword = ref<string>();
const HOST = inject('HOST');

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

const emits = defineEmits(["cancel"]);
const config = {
    headers: { Authorization: `Bearer ${localStorage.getItem("token")}` }
};

const submit = () => {
  if (validate()) {
    axios
        .put(`${HOST}/api/v0/profiles/passwords`, {
          "password": newPassword.value,
        }, config)
        .then((response) => {
          init({
            message: "Вы успешно обновили пароль!",
            color: "success",
          });
          emits("cancel");
        })
        .catch((error) => {
            init({
              message: "Что-то пошло не так.",
              color: "error",
            });

        });
    }
};


const newPasswordRules = [
  (v: string) => !!v || "Поле обязательно для заполнения!"
];

const repeatNewPasswordRules = [
  (v: string) => !!v || "Поле обязательно для заполнения!",
  (v: string) =>
    v === newPassword.value || "Пароли не совпадают",
];
</script>

<style lang="scss">
// TODO temporary before https://github.com/epicmaxco/vuestic-ui/issues/4020 fix
.va-modal__inner {
  min-width: 326px;
}
</style>
