<script setup>
    import { onMounted, reactive, ref, watch } from 'vue';
    import { useAuthStore } from '../stores/auth';
    import Spiner from '../components/ui/Spiner.vue';
    import CustomInput from '../components/ui/CustomInput.vue';
    import { storeToRefs } from 'pinia';
    import NotificationBadge from '../components/ui/NotificationBadge.vue';
    import FormChangePassword from '../components/FormChangePassword.vue';
    import FormChangeEmail from '../components/FormChangeEmail.vue';

    const auth = useAuthStore();

    const { user } = storeToRefs(auth);

    const loading = ref(false)
    const msgError = ref('');
    const msgSuccess = ref('');
    const form = ref(0);

    const userForm = reactive({
        name: '',
        lastName: '',
        phone1: '',
    })

    onMounted(() => {
      if(user.value) {
        getData()
      }
    })

    watch(user, async() => {
        if(user.value) {
            getData()
        } 
    });

    const getData = () => {
        userForm.name = user.value?.first_name  
        userForm.lastName = user.value?.last_name  
        userForm.phone1 = user.value?.phone

    }

    const handleSave = async() => {
        const error = validatiosUser();
        if(error != '') {
            msgError.value = error;
            clearMessages();
            return;
        }
        const userData = {
            "first_name" : userForm.name,
            "last_name" : userForm.lastName,
            "phone" : userForm.phone1,
        };
        loading.value = true;
        const result = await auth.updateProfile(userData)
        loading.value = false;
        if(result === null) {
            msgError.value = 'Algo salio mal, intente más tarde';
            clearMessages();
        } else {
            msgSuccess.value = 'Usuario actualizado';
            clearMessages();
        }
    }

    const clearMessages = () => {
        setTimeout(() => {
            msgError.value = '';
            msgSuccess.value = '';
        }, 3000);
   }


   const validatiosUser = () => {
        if(userForm.name.trim().length < 3) {
            return 'Ingresa nombre(s) valido';
        } else if(userForm.lastName.trim().length < 2) {
            return 'Ingresa apellido(s) valido';
        } else if(userForm.phone1.trim().length < 10) {
            return 'Ingresa teléfono valido';
        } else {
            return '';
        }
   }

   const setForm = (val) => {
        form.value = val
   }

</script>

<template>
    <div class="form-content">
        <div class="box-btns">
            <a class="btn-text" 
                :class="[(form === 0) ? 'selection' : '']"
                @click="setForm(0)"
            >Datos usuario</a>
            <a class="btn-text" 
                :class="[(form === 1) ? 'selection' : '']"
                @click="setForm(1)"
            >Cambiar correo</a>
            <a class="btn-text" 
                :class="[(form === 2) ? 'selection' : '']"
                @click="setForm(2)"
            >Cambiar contraseña</a>
        </div>
        <br/>
        <div class="divider"></div>
        <form 
            @submit.prevent="handleSave" 
            autocomplete="off" 
            method="post" 
            ref="formRef"
            v-if="form === 0"
        >
            <br/>
            <h3 class="title">Datos de usuario</h3>
            <br/>
            <NotificationBadge :msg="msgError" v-if="msgError != ''"/>
            <NotificationBadge :msg="msgSuccess" v-if="msgSuccess != ''" :is-error="false"/>
            <CustomInput
                label="Nombres(s)*:"
                type="text"
                name="name"
                :filled="false"
                v-model:field="userForm.name"
            />
            <CustomInput
                label="Apellidos(s)*:"
                type="text"
                name="lastname"
                :filled="false"
                v-model:field="userForm.lastName"
            />
            <CustomInput
                label="Teléfono*:"
                type="number"
                name="phone1"
                :step="1"
                :filled="false"
                v-model:field="userForm.phone1"
            />
            <div class="mt-5 text-center">
                <Spiner v-if="loading"/>
                <button 
                    v-else
                    class="btn btn-dark btn-block" type="submit">Guardar</button>
            </div> 
        </form>
        <FormChangeEmail v-if="form === 1"/>
        <FormChangePassword v-if="form === 2"/>
    </div>
           
</template>

<style scoped>
    /* .profile {
        margin: 0 auto;
    } */

    .box-btns {
        display: flex;
        justify-content: flex-end;
        gap: 2rem;
    }

    .selection {
        color: #333;
    }
    .form-content {
        margin-top: 1rem;
        max-width: 768px;
        /* width: 768px; */
        margin: 0 auto;
        background-color: #FFF;
        padding: 32px 32px;
        border-radius: 13px;
    }

    .content-phone{
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        /* gap: 5rem; */
    }

    .phone {
        width: 45%;
    }

    .btn-block {
        width: 80%;
    }

    @media (max-width: 1024px) {
        .form-content {
            margin: 24px 16px;
            background-color: #FFF;
            padding: 32px 32px;
            border-radius: 13px;
        }
    }

    @media (max-width: 568px) {
        .form-content {
            margin: 24px 8px;
            background-color: #FFF;
            padding: 20px 20px;
            border-radius: 13px;
        }

        .phone {
            width: 100%;
        }

        .content-phone{
            display: flex;
            flex-direction: column;
        }
    }
</style>