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

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

    const mi_url = new URL(document.location.href)
    const token = mi_url.searchParams.get('s')
    let persona = null

    infoTokenPassword({ token })
        .then(data => persona = data)
        .catch(error => error_token = error)

    // validar usuario contraseña
    async function onSave() {
        try {
            loading = true;
            message_error = ''
            const resultado = await crearPassword({ ...form, token })
            exito = resultado.ok;
        } 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">Crear nueva contraseña de acceso</h2>
        </div>
        <div class="card-body">
            {#if !exito}
                <form on:submit|preventDefault={onSave}>
                    {#if error_token}
                        <div class="alert alert-warning">😢 {error_token}</div>
                    {:else if !persona}
                        <div class="alert alert-info">Cargando información...</div>
                    {/if}

                    {#if persona?.nombres}
                        <h3>{persona.nombres} {persona.apellido_a} {persona.apellido_a}</h3>

                        <div class="mb-3">
                            <label class="form-label" for={null}>Código de seguridad</label>
                            <input class="form-control form-control-lg" type="text" bind:value={form.codigo} required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for={null}>Nueva contraseña</label>
                            <input class="form-control form-control-lg" type="password" bind:value={form.password} required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for={null}>Repita la contraseña</label>
                            <input class="form-control form-control-lg" type="password" bind:value={password_confirma} required>
                            {#if password_confirma !== form.password}
                                <div class="alert alert-warning">Las contraseñas no coinciden....</div>
                            {/if}
                        </div>
                    {/if}

                    {#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 || !form.password || password_confirma !== form.password || !form.codigo}>
                            <span class="fa fa-key mr-3"></span> Enviar
                        </button>
                    </div>
                </form>
            {:else}
                <div class="alert alert-success">
                    😃 Se ha guardado su nueva contraseña, puede volver e ingresar.
                </div>

                <a href="/">Volver</a>
            {/if}
        </div>
    </div>
</div>

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

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