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

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

    // validar usuario contraseña
    async function onRecuperar() {
        try {
            loading = true;
            message_error = ''
            const resultado = await recuperarAcceso(form);
            exito = resultado.ok;
            console.log({ resultado })
        } 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">Recuperar Acceso</h2>
        </div>
        <div class="card-body">
            {#if !exito}
                <form on:submit|preventDefault={onRecuperar}>
                    <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}>Correo Electrónico</label>
                        <input class="form-control form-control-lg" type="email" bind:value={form.email} required placeholder="usuario@correo.com">
                    </div>

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

                    <Link to="/">Volver</Link>

                    <div class="text-center mt-3">
                        <button type="submit" class="btn btn-dark" disabled={loading}>
                            <span class="fa fa-key mr-3"></span> Enviar
                        </button>
                    </div>
                </form>
            {:else}
                <div class="alert alert-success">
                    <p>Se le ha enviado un correo electrónico con instrucciones para crear una nueva contraseña</p>
                </div>
            {/if}
        </div>
    </div>
</div>

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

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