<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 { recoveryPassword, recoveryPasswordConfirm, regiter } from '../services/auth';
    import { useAuthStore } from '../stores/auth';
    import { useRouter } from 'vue-router';
    import { useNotificationsStore } from '../stores/notifications';
    import { useI18n } from 'vue-i18n';
    
    const pwdForm = reactive({
        pwd: '',
        pwd2: '',
        code: '',
        checksum: '',
    })

    const step = ref(1);

    const auth = useAuthStore();
    const router = useRouter();
    const notifications = useNotificationsStore()

    const loading = ref(false)
    const msgError = ref('');
    const msgSuccess = ref('');
    const { t } = useI18n()

    const hangleSave = async() => {
        msgError.value = '';
        msgSuccess.value = '';
        let resp = validations();
        if(resp !== '') {
            msgError.value = resp;
            clearMessages();
            return;
        } else {
            loading.value = true;
            msgError.value = '';
            const data = {
                email: auth.user.email,
                password: pwdForm.pwd
            }
            const result = await recoveryPassword(data);
            if(result.msg === 'success' && result.data !== null) {
                msgSuccess.value = t('messages.sendCode')
                pwdForm.checksum = result.data.checksum;
                step.value = 2;
                clearMessages();
            } else {
                msgError.value = result.msg;
                clearMessages();
            }
            loading.value = false;
        }
    }

    const handleConfirmChange = async() => {
        msgError.value = '';
        msgSuccess.value = '';
        if(pwdForm.code.length < 6) {
            msgError.value = t('errors.code');
            clearMessages();
            return;
        } else {
            loading.value = true;
            msgError.value = '';
            const data = {
                email: auth.user.email,
                password: pwdForm.pwd,
                otp: pwdForm.code,
                checksum: pwdForm.checksum
            }
            const result = await recoveryPasswordConfirm(data);
            // console.log(result);
            if(result.msg === 'success' && result.data !== null){
                Object.assign(pwdForm, {
                    pwd: '',
                    retryPwd: '',
                    code: '',
                    checksum: '',
                });
                clearMessages();
                notifications.$patch({
                    text : t('messages.changePassword'),
                    show : true,
                    error: false
                });
                auth.logout();
                router.push({name: 'login'});
            } else {
                msgError.value = result.msg;
               clearMessages()
            }
            loading.value = false;
        }
    }

    const resendCode = async() => {
        // loading.value = true;
        // const data = {
        //     email: pwdForm.email,
        //     password: pwdForm.pwd
        // }
        // const result = await regiter(data);
        // if(result.msg === 'success' && result.data !== null) {
        //     msgSuccess.value = 'Te enviamos un código al correo, ingresado!';
        //     checksum.value = result.data.checksum;
        //     clearMessages();
        // } else {
        //     msgError.value = result.msg;
        //     clearMessages();
        // }
        // loading.value = false;
   }

    const handleBack = (val) => {
        step.value = val;
   }

    const validations = () => {
        const pass = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/;

        if(!pass.test(pwdForm.pwd)) {
            return t('errors.weakPassword')
        } else if (pwdForm.pwd !== pwdForm.pwd2) {
            return t('errors.matchPassword');
        } else {
            return '';
        }
   }

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

<template>
    <form 
        @submit.prevent="hangleSave" 
        autocomplete="off" 
        method="post" 
        ref="formRef1"
        v-if="step === 1"
    >
        <br/>   
        <h3 class="title">{{ t('profile.changePassword') }}</h3>
        <br/>
        <NotificationBadge :msg="msgError" v-if="msgError != ''"/>
        <NotificationBadge :msg="msgSuccess" v-if="msgSuccess != ''" :is-error="false"/>
        <CustomInput
            :label="t('labels.password2') + '*:'"
            type="password"
            name="pwd"
            :filled="false"
            v-model:field="pwdForm.pwd"
            :help-text="t('login.helptext')"
        />
        <CustomInput
            :label="t('labels.password3') + '*:'"
            type="password"
            name="pwd2"
            :step="1"
            :filled="false"
            v-model:field="pwdForm.pwd2"
        />
        <div class="warning-info">
            <div><i class="fa-solid fa-triangle-exclamation warning"></i></div>
            {{ t('profile.helpTextResetPass') }}
        </div>
        <div class="mt-5 text-center">
            <Spiner v-if="loading"/>
            <button 
                v-else
                class="btn btn-dark btn-block" type="submit">{{ t('buttons.continue') }}</button>
        </div> 
    </form>
    <form v-if="step === 2" @submit.prevent="handleConfirmChange" class="mx-5">
        <div class="d-flex justify-content-center align-items-center mb-4 mt-4">
            <a  
                @click="handleBack(1)"
                class="btn-text ms-2"><i class="fa-solid fa-arrow-left"></i> {{ t('buttons.back') }}</a>
        </div>
        <NotificationBadge :msg="msgError" v-if="msgError != ''"/>
        <NotificationBadge :msg="msgSuccess" :is-error="false" v-if="msgSuccess != ''"/>
        <p class="help-info">{{ t('login.helptextCode') }}</p>
        <CustomInput 
            :label="t('labels.code') + '*:'"
            name="code"
            :filled="false"
            type="text"
            v-model:field="pwdForm.code"
        />
        <!-- <div v-if="!loading" class="d-flex justify-content-center align-items-center mt-4">
            <a  
                @click="resendCode()"
                class="btn-text ms-2"><i class="fa-solid fa-rotate-right"></i> Reenviar código</a>
        </div> -->
        <div class="mt-5 text-center">
            <Spiner v-if="loading"/>
            <button 
                v-else
                class="btn btn-dark btn-block" type="submit">{{ t('buttons.confirm') }}</button>
        </div> 
    </form>
</template>

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