<script setup>
    import { reactive, ref } from 'vue';
    import CustomInput from '../components/ui/custominput.vue';
    import NotificationBadge from '../components/ui/NotificationBadge.vue';
    import {validateEmail} from '../helpers/validations';
    import {regiter, regiterConfirm} from "../services/auth";
    import Spiner from '../components/ui/Spiner.vue';
    import { useRouter } from 'vue-router';
    import { useNotificationsStore } from '../stores/notifications';

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

    const form = reactive({
        email: '',
        pwd: '',
        retryPwd: '',
        code: ''
    });

    const step = ref(1);
    const loading = ref(false);
    const checksum = ref('');
    const msgError = ref('');
    const msgSuccess = ref('');

    const handleRegister = async() => {
        msgError.value = '';
        msgSuccess.value = '';
        let resp = validations();
        if(resp !== '') {
            msgError.value = resp;
            clearMessages();
            return;
        } else {
            loading.value = true;
            msgError.value = '';
            const data = {
                email: form.email,
                password: form.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;
                step.value = 2;
                clearMessages();
            } else {
                msgError.value = result.msg;
                clearMessages();
            }
            loading.value = false;
        }
    }


    const handleConfirmRegister = async() => {
        msgError.value = '';
        msgSuccess.value = '';
        if(form.code.length < 6) {
            msgError.value = 'Ingresa código valido';
            clearMessages();
            return;
        } else {
            loading.value = true;
            msgError.value = '';
            const data = {
                email: form.email,
                password: form.pwd,
                otp: form.code,
                checksum: checksum.value
            }
            const result = await regiterConfirm(data);
            // console.log(result);
            if(result.msg === 'success' && result.data !== null){
                msgSuccess.value = 'Registro exitoso!';
                step.value = 3;
                checksum.value = '';
                Object.assign(form, {
                    email: '',
                    pwd: '',
                    retryPwd: '',
                    code: ''
                });
                clearMessages();
                notifications.$patch({
                    text : 'Registro exitoso, Inicie sesión!',
                    show : true,
                    error: false
                });
                router.push({name: 'login'});
            } else {
                msgError.value = result.msg;
               clearMessages()
            }
            loading.value = false;
        }
    }

    const validations = () => {
        const pass = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/;
        if(form.email.trim() == '' || form.pwd.trim() == '' || form.retryPwd.trim() == '') {
            return 'Todos los campos con obligatorios';
        } else if (!validateEmail(form.email)) {
            return 'Correo electrónico no es valido'
        } else if(!pass.test(form.pwd)) {
            return 'Contraseña poco segura';
        } else if (form.pwd != form.retryPwd) {
            return 'Las contraseñas no coinciden';
        } else {
            return '';
        }
   }

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

   const resendCode = async() => {
        loading.value = true;
        const data = {
            email: form.email,
            password: form.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;
   }
</script>

<template>
        <div class="d-flex flex-column my-5 justify-content-center align-items-center">
            <h2 class="title">Registro de nuevos usuarios</h2>
            <div class="form-content">
                <form v-if="step === 1" @submit.prevent="handleRegister">
                    <NotificationBadge :msg="msgError" v-if="msgError != ''"/>
                    <NotificationBadge :msg="msgSuccess" :is-error="false" v-if="msgSuccess != ''"/>
                    <CustomInput 
                        label="Ingresa tu correo electrónico"
                        name="email"
                        type="email"
                        v-model:field="form.email"
                    />
                    <CustomInput 
                        label="Contraseña"
                        name="password"
                        type="password"
                        v-model:field="form.pwd"
                        help-text="La Contraseña debe ser mínimo 8 caracteres, al menos una mayúscula, al menos una minúscula, y un digito."
                    />
                    <CustomInput 
                        label="Confirma Contraseña"
                        name="retryPassword"
                        type="password"
                        v-model:field="form.retryPwd"
                    />
                    <Spiner v-if="loading" class="mt-5"/>
                    <input 
                        v-else
                        type="submit" 
                        class="btn-primary-lg btn-lg-block radius-1 mt-5" value="Continuar">
                    
                    <p class="mt-5 fs-6 text-center">Al registrarte aceptas nuestros <RouterLink class="btn-text" :to="{name: 'login'}">términos y cóndiciones</RouterLink></p>
                    <p class="mt-5 fs-6 text-center">¿Ya tienes una cuenta? <RouterLink class="btn-text" :to="{name: 'login'}">Ingresa aqui</RouterLink></p>
                    
                </form>
                <form v-if="step === 2" @submit.prevent="handleConfirmRegister" class="mx-5">
                    <div class="d-flex justify-content-center align-items-center mb-4">
                        <a  
                            @click="handleBack(1)"
                            class="btn-text ms-2"><i class="fa-solid fa-arrow-left"></i> Volver</a>
                    </div>
                    <NotificationBadge :msg="msgError" v-if="msgError != ''"/>
                    <NotificationBadge :msg="msgSuccess" :is-error="false" v-if="msgSuccess != ''"/>
                    <p class="help-info">Te enviamos un código de verificación al correo electrónico, ingresalo para confirmar registro. No olvides revisar en la carpeta spam</p>
                    <CustomInput 
                        label="Ingresa el código"
                        name="code"
                        type="text"
                        v-model:field="form.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>
                    <Spiner v-if="loading" class="mt-5"/>
                    <input 
                        v-else
                        type="submit" 
                        class="btn-primary-lg btn-lg-block radius-1 mt-5" value="Continuar">
                </form>
            </div>
        </div>
</template>

<style scoped>
    .form-content {
        width: 100%;
        padding: 2rem 3rem;
    }

    .icon-success{
        font-size: 5rem;
        color: green;
    }

    .help-info {
        margin-bottom: 2rem;
        font-size: 1.2rem;
        font-weight: 400;
        color: #5a4b4b;
    }
    .msg-success {
        margin-bottom: 2rem;
        font-size: 1.4rem;
        font-weight: 500;
        color: #5a4b4b;
    }

    @media (max-width: 1224px) {
        .form-content {
            width: 80%;
        }
    }

    @media (max-width: 768px) {
        .form-content {
            width: 100%;
            padding: 2rem 1rem;
        }
    }
</style>