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

    let form = { rut: '', pass: '' }
    let message_error = '';
    let loading = false;

    // validar usuario contraseña
    async function onIngresar() {
        try {
            loading = true;
            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)
        } finally {
            loading = false;
        }
    }
</script>

<div class="container p-4 bg-neutral box-login">
    <div style="margin-top: 100px;"></div>
    <div class="card mb-4 m-auto">
        <div class="card-header bg-dark text-center p-3">
            <h2 class="text-light">Acceso</h2>
        </div>
        <div class="card-body">
            <form on:submit|preventDefault={onIngresar}>
                <div class="mb-3">
                    <label class="form-label" for={null}>RUT</label>
                    <InputRut bind:value={form.rut} class="form-control form-control-lg" required placeholder="12.345.678-9" />
                </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-dark" disabled={loading}>
                        <span class="fa fa-key mr-3"></span>
                        Ingresar al sistema
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
    .box-login {
        height: 100vh;
        max-width: inherit;
    }

    .box-login .card {
        width: 400px;
        max-width: 100%;
        min-width: 200px;
    }
</style>