<script>
    import { Link } from 'svelte-navigator'
    import Paginate from '$/components/Paginate.svelte'
    import PageTitle from '$/components/PageTitle.svelte'
    import { getUsuarios } from '$/services/usuarios'

    let usuarios = { count: 0, results: [] }
    let page = 1
    const limit = 15
    let loading = false

    $: onPage(page)

    async function onPage(page) {
        try {
            loading = true
            const offset = (page - 1) * limit;
            usuarios = await getUsuarios({ offset, limit, ordering: 'login' })
        } catch(error) {
            alert(error.detail || error)
        } finally {
            loading = false;
        }
    }
</script>

<PageTitle {loading}>Usuarios</PageTitle>

<div class="card">
    <div class="card-header">
        <div class="mb-3 d-flex">
            <Link to='/usuarios/nuevo' class="btn btn-primary">
                <i class="bi bi-plus-lg"></i> Nuevo
            </Link>
            <div class="m-auto"></div>
            <Link to='/' class="btn btn-outline-secondary">Volver</Link>
        </div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead>
                    <tr class="table-light">
                        <th>Login</th>
                        <th>Nombres</th>
                        <th>Apellido 1</th>
                        <th>Apellido 2</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody>
                    {#each usuarios.results as row}
                    <tr>
                        <td><Link to={"/usuarios/" + row.login}>{row.login}</Link></td>
                        <td>{row.persona.nombres}</td>
                        <td>{row.persona.apellido_a}</td>
                        <td>{row.persona.apellido_b}</td>
                        <td>{row.persona.email}</td>
                    </tr>
                    {/each}
                </tbody>
            </table>
        </div>
    </div>
    <div class="card-footer d-flex">
        <a href={"#"} class="btn btn-outline-secondary me-3" on:click|preventDefault={() => onPage(page)}>
            <i class="bi bi-arrow-repeat"></i>
        </a>
        <Paginate
            offset={(page - 1) * limit}
            {limit}
            count={usuarios.count}
            on:page={ev => page = ev.detail}
        />
    </div>
</div>

<style>
    .table-responsive {
        max-height: calc(100vh - 300px);
    }
</style>