<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';
    import { useI18n } from 'vue-i18n';

    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: '',
    })

    const { t } = useI18n()

    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.msg === 'success') {
            msgSuccess.value = t('errors.msgUpdateUser');
            clearMessages();
        } else {
            msgError.value = t('errors.generic');
            clearMessages();
        }
    }

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


   const validatiosUser = () => {
        if(userForm.name.trim().length < 3) {
            return t('errors.name');
        } else if(userForm.lastName.trim().length < 2) {
            return t('errors.lastname');
        } else if(userForm.phone1.trim().length < 10) {
            return t('errors.phone');
        } 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)"
            >{{ t('profile.profile') }}</a>
            <a class="btn-text" 
                :class="[(form === 1) ? 'selection' : '']"
                @click="setForm(1)"
            >{{ t('profile.changeEmail') }}</a>
            <a class="btn-text" 
                :class="[(form === 2) ? 'selection' : '']"
                @click="setForm(2)"
            >{{ t('profile.changePassword') }}</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">{{ t('profile.profile') }}</h3>
            <br/>
            <NotificationBadge :msg="msgError" v-if="msgError != ''"/>
            <NotificationBadge :msg="msgSuccess" v-if="msgSuccess != ''" :is-error="false"/>
            <CustomInput
                :label="t('labels.names')+'*:'"
                type="text"
                name="name"
                :filled="false"
                v-model:field="userForm.name"
            />
            <CustomInput
                :label="t('labels.lastnames')+'*:'"
                type="text"
                name="lastname"
                :filled="false"
                v-model:field="userForm.lastName"
            />
            <CustomInput
            :label="t('labels.phone')+'*:'"
                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">{{ t('buttons.save') }}</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>