<script setup>
    import {reactive, ref} from 'vue';
    import CustomInput from './ui/CustomInput.vue';
    import Spiner from './ui/Spiner.vue';
    import NotificationBadge from './ui/NotificationBadge.vue';
    import { validateEmail } from '../helpers/validations';
    import Swal from 'sweetalert2';
    import { useAuthStore } from '../stores/auth';
    import { useNotificationsStore } from '../stores/notifications';
    import { useRouter } from 'vue-router';
    import { useI18n } from 'vue-i18n';

    const emailForm = reactive({
        email: '',
        email2: '',
    })

    const loading = ref(false)
    const msgError = ref('');
    const msgSuccess = ref('');
    const auth = useAuthStore();
    const notifications = useNotificationsStore();
    const router = useRouter();

    const { t } = useI18n();

    const hangleSave = () => {
        msgError.value = '';
        msgSuccess.value = '';
        let resp = validations();
        if(resp !== '') {
            msgError.value = resp;
            clearMessages();
            return;
        } else {
            Swal.fire({
                title: t('profile.questionChangeEmail'),
                // text: '',
                html: t('profile.msgInfoEmail'),
                icon: 'warning',
                showCancelButton: true,
                cancelButtonColor: "#d33",
                confirmButtonText: t('buttons.confirm'),
                cancelButtonText: t('buttons.cancel'),
            }).then( async(result) => {
                if(result.isConfirmed) {
                    Swal.fire({
                        title:  t('messages.loading'),
                        html: t('messages.savingChanes') + '...',
                        allowOutsideClick: false,
                        didOpen: () => {
                            Swal.showLoading()
                        },
                    });

                    const userData = {
                        "email" : emailForm.email,
                    };
                    // console.log(userData);
                    loading.value = true;
                    const response = await auth.updateProfile(userData)
                    loading.value = false;
                    if (response.msg !== 'success') {
                        msgError.value = response.msg;
                        clearMessages();
                    } else {
                        clearMessages();
                        notifications.$patch({
                            text : t('profile.msgChangeEmail'),
                            show : true,
                            error: false
                        });
                        auth.logout();
                        router.push({name: 'login'});
                    }
                    Swal.close()

                }

            });
        }
    }

    const validations = () => {
        if(emailForm.email.trim() == '') {
            return t('errors.requireds');
        } else if (!validateEmail(emailForm.email)) {
            return t('errors.email')
        } else if (emailForm.email !== emailForm.email2) {
            return t('errors.notMatchEmails')
        } else {
            return '';
        }
   }

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

<template>
    <form 
        @submit.prevent="hangleSave" 
        autocomplete="off" 
        method="post" 
        ref="formRef1"
    >
        <br/>
        <h3 class="title">{{ t('profile.titleFormEmail') }}</h3>
        <br/>
        <NotificationBadge :msg="msgError" v-if="msgError != ''"/>
        <NotificationBadge :msg="msgSuccess" v-if="msgSuccess != ''" :is-error="false"/>
        <CustomInput
            :label="t('profile.newEmail') + '*:'"
            type="email"
            name="email"
            :filled="false"
            v-model:field="emailForm.email"
        />
        <CustomInput
            :label="t('profile.confirmEmail') + '*:'"
            type="email"
            name="email2"
            :step="1"
            :filled="false"
            v-model:field="emailForm.email2"
        />
        <div class="warning-info">
            <div>
                <i class="fa-solid fa-triangle-exclamation warning"></i>
            </div>
            <span v-html="t('profile.msgInfoEmail')"></span>
        </div>
        <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>
</template>

<style scoped>
     /* .box-back-btn {
        display: flex;
        justify-content: center;
        padding: 16px 0px;
    } */

    .warning-info {
        display: flex;
        padding: 16px;
        background: rgb(223, 223, 161);
        font-size: 0.9rem;
        justify-items: center;
        align-items: center;
        font-weight: 400;
        color: rgb(86, 57, 57);
        border-radius: 13px;
    }

    .warning {
        font-size: 33px;
        margin-right: 12px;
        /* color: white; */
    }

    .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>