<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 Spiner from '../components/ui/Spiner.vue';
    import { login } from '../services/auth';
    import { RouterLink, useRouter } from 'vue-router';
    import { useAuthStore } from '../stores/auth';

    const form = reactive({
        email: '',
        password: '',
    });

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

    const loading = ref(false);
    const msgError = ref('');
    const msgSuccess = ref('');

    const handleLogin = 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.password
            }
            const resp = await login(data);
            if(resp.msg === 'success') {
                if( resp.data.user.company ) { // Registro completo
                    localStorage.setItem('session', resp.data.session_token);
                    localStorage.setItem('access', resp.data.accessToken);
                    localStorage.setItem('id', resp.data.user.company);
                    console.log('id', resp.data.user.company)
                    router.push({name: 'home'});
                    auth.$patch({
                        sesion: resp.data.session_token,
                        token: resp.data.accessToken,
                        user: resp.data.user,
                    })
                } else { // Completar registro
                    auth.$patch({
                        sesion: resp.data.session_token,
                        token: resp.data.accessToken,
                        user: resp.data.user,
                    })
                    // localStorage.setItem('session', resp.data.session_token);
                    // localStorage.setItem('access', resp.data.accessToken);
                    router.push({name: 'register-company'});
                }
            } else {
                msgError.value = resp.msg;
            }
            clearMessages();
            loading.value = false;
        }
    }

    const validations = () => {
        if(form.email.trim() == '' || form.password.trim() == '') {
            return 'Todos los campos con obligatorios';
        } else if (!validateEmail(form.email)) {
            return 'Correo electrónico no es valido'
        } else {
            return '';
        }
   }

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

</script>

<template>
    <div class="d-flex flex-column my-5 justify-content-center align-items-center">
        <h2 class="title">Iniciar sesión</h2>
        <p class="subtitle mt-4 mb-5 text-center">Bienvenido de vuelta! Ingresa tu email y contraseña</p>
        <form  @submit.prevent="handleLogin" class="form-content">
            <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.password"
            />
            <Spiner v-if="loading" class="mt-5"/>
            <input 
                v-else
                type="submit" 
                class="btn-primary-lg btn-lg-block radius-1 mt-5" value="Ingresar">
        </form>
        <p class="mt-3 fs-6">¿Olvidaste tu contreseña? <RouterLink class="btn-text" :to="{name: 'recovery'}">Ingresa aqui</RouterLink></p>
        <p class="mt-5 fs-6">¿No tienes una cuenta? <RouterLink class="btn-text" :to="{name: 'register'}">Registrate aqui</RouterLink></p>
                
    </div>
</template>

<style scoped>
    .subtitle {
        font-size: 1.4rem;
        font-weight: 500;
        color: grey;
    }
    .form-content {
        display: flex;
        flex-direction: column;
        width: 100%;
        /* min-width: 420px; */
        /* 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>