<template>
  <VaModal
    :mobile-fullscreen="false"
    size="small"
    hide-default-actions
    max-width="380px"
    model-value
    close-button
    @update:modelValue="emits('cancel')"
  >
    <h1 class="va-h5 mb-4">Изменить имя</h1>
    <VaForm ref="form" @submit.prevent="submit">
      <VaInput v-model="Name" class="mb-4" label="Имя" placeholder="Имя" />
      <VaInput v-model="Surname" class="mb-4" label="Фамилия" placeholder="Фамилия" />
      <div
        class="flex flex-col-reverse md:flex-row md:items-center md:justify-end 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"
        >
          Save</VaButton
        >
      </div>
    </VaForm>
  </VaModal>
</template>
<script lang="ts" setup>
import { inject } from 'vue'
import { ref } from "vue";
import axios from "axios";

import { useUserStore } from "../../../stores/user-store";

import { buttonStyles } from "../styles";
import { useToast } from "vuestic-ui/web-components";

const store = useUserStore();

const { init } = useToast();

const emits = defineEmits(["cancel"]);

const Name = ref<string>(store.userName);
const Surname = ref<string>(store.userSurname);
const HOST = inject('HOST');

const submit = () => {
  if (!Name.value && !Surname.value) {
    return emits("cancel");
  }
  if (Surname.value === store.userSurname && Name.value === store.userName) {
    return emits("cancel");
  }
  let dataProfile = JSON.parse(localStorage.getItem("profile")!);
  dataProfile.first_name = Name.value;
  dataProfile.surname = Surname.value;
  const config = {
      headers: { Authorization: `Bearer ${localStorage.getItem("token")}` }
  };
  axios
      .patch(`${HOST}/api/v0/profiles/${store.profileID}`, {
        "profile": dataProfile,
      }, config)
      .then((response) => {
        store.changeUserName(Name.value, Surname.value);
      })
      .catch((error) => {
          init({
            message: "Что-то пошло не так.",
            color: "error",
          });

      });

  init({ message: "Вы успешно изменили имя!", color: "success" });
  emits("cancel");
};
</script>

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