<script>
    import { Link } from 'svelte-navigator'
    import { createToken } from '$/services/login'

    let form = { username: '', pass: '' }
    let message_error = '';

    // validar usuario contraseña
    async function onIngresar() {
        try {
            message_error = ''
            const { token } = await createToken(form)
            sessionStorage.setItem('token', token)
            document.location.reload();
        } catch(error) {
            message_error = error.message || error
            setTimeout(() => message_error = '', 3000)
        }
    }
</script>

<div class="card">
    <div class="card-body">
        <div class="m-sm-4">
            <div class="text-center mb-4">
                <img src="/avatars/avatar2.png" alt="Avatar"
                    class="img-fluid rounded-circle" width="132" height="132"
                />
            </div>
            <form on:submit|preventDefault={onIngresar}>
                <div class="mb-3">
                    <label class="form-label" for={null}>Cuenta</label>
                    <input class="form-control form-control-lg" type="text" bind:value={form.username} required
                        placeholder="Ingrese su cuenta de usuario">
                </div>
                <div class="mb-3">
                    <label class="form-label" for={null}>Contraseña</label>
                    <input class="form-control form-control-lg" type="password" bind:value={form.password} required
                        placeholder="Ingrese su contraseña">
                </div>

                {#if message_error}
                    <div class="mb-3 text-danger">{message_error}</div>
                {/if}

                <Link to="/recovery">Olvido su contraseña?</Link>
                
                <div class="text-center mt-3">
                    <button type="submit" class="btn btn-lg btn-primary">Ingresar al sistema</button>
                </div>
            </form>
        </div>
    </div>
</div>
