<script>
    import { Link, useLocation } from 'svelte-navigator'
    import Paginate from '$/components/Paginate.svelte'
    import PageTitle from '$/components/PageTitle.svelte'
    import { getComunas, getComuna, createComuna, updateComuna, deleteComuna } from '$/services/comunas'
    import Modal from '$/components/Modal.svelte';
    import FormComuna from './Form.svelte';
    import { getPermisosPath } from '$/services/usuarios';

    let comuna = null
    let es_nuevo = true
    let comunas = { count: 0, results: [] }
    let page = 1
    let loading = false;
    const limit = 15
    let escritura = false;
    let location = useLocation()

    getPermisosPath($location.pathname)
        .then(data => escritura = data.escritura)
        .catch(error => console.log({ error }))
    
    $: onPage(page)

    async function onPage(page) {
        try {
            loading = true
            const offset = (page - 1) * limit;
            comunas = await getComunas({ offset, limit, ordering: 'id_region' })
        } catch(error) {
            globalThis.toast.success(error.detail || error)
        } finally {
            loading = false
        }
    }

    function onNuevo() {
        comuna = {}
        es_nuevo = true
    }

    async function onEditar({ id_comuna }) {
        try {
            loading = true
            comuna = await getComuna(id_comuna)
            es_nuevo = false
        } catch (error) {
            globalThis.toast.success(error.detail || error)
        } finally {
            loading = false
        }
    }

    async function onSave() {
        try {
            if (es_nuevo) {
                await createComuna(comuna)
            } else {
                await updateComuna(comuna)
            }
            globalThis.toast.success('Comuna guardada con exito')
            comuna = null; // se cierra el modal
            onPage(page) // refresco la tabla de registros
        } catch (error) {
            globalThis.toast.success(error.detail || error)
        }
    }

    async function onDelete() {
        try {
            if (!confirm(`Desea eliminar la comuna [${comuna.nombre_comuna}]?`)) return;
            await deleteComuna(comuna.id_comuna)
            globalThis.toast.success('Comuna eliminada con exito')
            comuna = null; // se cierra el modal
            onPage(page) // refresco la tabla de registros
        } catch (error) {
            globalThis.toast.success(error.detail || error)
        }
    }
</script>

<PageTitle {loading}>Comunas</PageTitle>

<div class="card">
    <div class="card-header">
        <div class="mb-3 d-flex">
            {#if escritura}
                <button class="btn btn-primary me-3"
                    on:click|preventDefault={onNuevo}>
                    <i class="bi bi-plus-lg"></i> Nuevo
                </button>
            {/if}
            <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>ID</th>
                        <th>Nombre</th>
                        <th>Región</th>
                    </tr>
                </thead>
                <tbody>
                    {#each comunas.results as row}
                    <tr>
                        <td><a class="d-block" href={"#"} on:click|preventDefault={() => onEditar(row)}>{row.id_comuna}</a></td>
                        <td>{row.nombre_comuna}</td>
                        <td>{row.id_region}</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
            forcePage={page}
            {limit}
            count={comunas.count}
            on:page={ev => page = ev.detail}
        />
    </div>
</div>


{#if !!comuna}
    <form action="" on:submit|preventDefault={onSave}>
        <Modal title="Comuna"
            on:close={() => comuna = null}
        >
            <div class={escritura ? "" : "disabled"}>
                <FormComuna bind:form={comuna} {es_nuevo} />
            </div>

            <svelte:fragment slot="buttons">
                {#if escritura}
                    <button type="submit" class="btn btn-primary">Guardar</button>
                {/if}
                {#if !es_nuevo && escritura}
                    <button class="btn btn-danger" on:click|preventDefault={onDelete}>Eliminar</button>
                {/if}
            </svelte:fragment>
        </Modal>
    </form>
{/if}

<style>
    .table-responsive { max-height: calc(100vh - 300px); }
    .disabled { pointer-events: none !important; }
</style>