<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';
    import { useAuthStore } from '../stores/auth';
    import { useI18n } from 'vue-i18n';

    const router = useRouter();
    const notifications = useNotificationsStore()
    const auth = useAuthStore();
    const { t } = useI18n()

    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 = t('messages.sendCode');
                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 = t('errors.code');
            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 : t('messages.register'),
                    show : true,
                    error: false
                });
                auth.$patch({
                    sesion: result.data.session_token,
                    token: result.data.accessToken,
                    user: result.data.user,
                })
                router.push({name: 'register-company'});
            } 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 t('errors.requireds');
        } else if (!validateEmail(form.email)) {
            return t('errors.email')
        } else if(!pass.test(form.pwd)) {
            return t('errors.weakPassword');
        } else if (form.pwd != form.retryPwd) {
            return t('errors.matchPassword');
        } 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 = t('messages.sendCode');
            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">{{ t('login.register') }}</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="t('labels.email')"
                        name="email"
                        type="email"
                        v-model:field="form.email"
                    />
                    <CustomInput 
                        :label="t('labels.password')"
                        name="password"
                        type="password"
                        v-model:field="form.pwd"
                        :help-text="t('login.helptext')"
                    />
                    <CustomInput 
                        :label="t('labels.password3')"
                        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="t('buttons.continue')">
                    
                    <p class="mt-5 fs-6 text-center">
                        {{ t('login.notice') }} 
                        <RouterLink 
                            class="btn-text me-1" 
                            :to="{name: 'terms-conditions'}" 
                            target="_blank">{{t('buttons.terms')}}</RouterLink>
                        {{  t('global.and') }}
                        <RouterLink 
                            class="btn-text ms-1" 
                            :to="{name: 'notice-privacy'}" 
                            target="_blank"> {{ t('buttons.noticePrivacity') }}</RouterLink>
                    </p>
                    <p class="mt-5 fs-6 text-center"> {{t('login.questionAccount')}} <RouterLink class="btn-text" :to="{name: 'login'}">{{ t('buttons.enter') }}</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> {{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"
                        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> {{ t('buttons.resendCode') }}</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="t('buttons.continue')">
                </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>