<template>
  <form @submit.stop="onSubmit">
    <div class="row">
      <div class="col-xxl-6 col-md-6">
        <div class="profile__input-box mb-3">
          <div class="profile__input mb-0">
            <input type="text" placeholder="Nombre completo" v-model="name" />
            <span>
              <svg-user-3 />
            </span>
          </div>
          <err-message :msg="errors.name" />
        </div>
      </div>
      <div class="col-xxl-6 col-md-6">
        <div class="profile__input-box mb-3">
          <div class="profile__input mb-0">
            <input 
              type="text" 
              placeholder="Escribe tu número telefónico" 
              minlength="10"
              maxlength="11"
              v-model="cellphone" 
              v-on:keypress="utilsStore.validateOnlyNumber" 
            />
            <span>
              <svg-phone-2 />
            </span>
          </div>
          <err-message :msg="errors.cellphone" />
        </div>
      </div>
      <div class="col-xxl-12">
        <div class="profile__btn d-flex justify-content-end">
          <button type="submit" class="tp-btn d-flex justify-content-center">
            <span v-if="!show_loader">Actualizar datos</span>
            <SharedLoader v-if="show_loader" :width="20" :height="20" />
          </button>
        </div>
      </div>
    </div>
  </form>
</template>

<script setup lang="ts">
import type { UpdateUserInfoInterface } from "@/pinia/auth/login/interfaces/update_user_info.interface";
import { useLoginStore } from "@/pinia/auth/login/login.store";
import { useUtilsStore } from "@/pinia/utils/utils.store";
import { useField, useForm } from "vee-validate";
import { toast } from "vue3-toastify";
import * as yup from "yup";

const utilsStore = useUtilsStore();
const loginStore = useLoginStore();

const show_loader = ref(false);

const { errors, handleSubmit, setValues, values, resetForm } = useForm<UpdateUserInfoInterface>({
  validationSchema: yup.object({
    name: yup.string()
      .min(5, 'Mínimo 5 caracteres')
      .required('El nombre completo es requerido.'),
    cellphone: yup.string()
      .min(10, 'El número telefónico debe tener al menos 10 dígitos')
      .max(11, 'El número telefónico debe tener máximo 11 dígitos')
      .required('El número telefónico es requerida.'),
  }),
  initialValues: {
    name: loginStore.user ? loginStore.user.name : '',
    cellphone: loginStore.user ? loginStore.user.cellphone : '',
  }
});

const { value: name } = useField("name");
const { value: cellphone } = useField("cellphone");

const onSubmit = handleSubmit(async (value) => {
  show_loader.value = true;
  const updated = await loginStore.updateUserInfo(value);
  show_loader.value = false;

  if(updated) {
    toast.success('Los datos se han actualizado correctamente', {position: 'bottom-center'});
  } else {
    toast.error('Hubo un error al actualizar los datos', {position: 'bottom-center'});
  }
})
</script>
