<script>
    import { onMount } from 'svelte'
    import { storeLayout, storePermisoApp } from '$/stores/global'
    import FormPersona from './Form.svelte'
    import { Link, useParams, useNavigate } from 'svelte-navigator';
    import { getPersona, createPersona, updatePersona } from '$/services/personas';
    import PageTitle from '../../components/PageTitle.svelte';

    onMount(() => {
        $storeLayout.showSidebar = false;
        return () => {
            $storeLayout.showSidebar = true;
        }
    })

    const params = useParams()
    const navigate = useNavigate()
    let es_nuevo = true;
    let form = { photo: null }
    let loading = false;
    let escritura = false

    $: escritura = $storePermisoApp?.personas?.escritura;
    $: es_nuevo = !$params.rut
    $: begin($params)

    async function begin({ rut = null }) {
        try {
            if (!rut) return; // si es nuevo, no busco informacion
            loading = true
            form = await getPersona(rut)
        } catch (error) {
            globalThis.toast.success(error.detail || error)
        } finally {
            loading = false
        }
    }

    async function onSave() {
        try {
            if (es_nuevo) {
                // para crear un usuario, es requerido enviar los datos de la persona ademas.
                await createPersona(form)
            } else {
                await updatePersona(form)
            }
            globalThis.toast.success('Datos guardados con exito!')
            navigate('/personas')
        } catch (error) {
            globalThis.toast.success(error.detail || error)
        }
    }
</script>

<PageTitle {loading}>{es_nuevo ? 'Nuevo Persona': 'Editar Persona'}</PageTitle>

<form action="" on:submit|preventDefault={onSave}>
    <div class="card">
        <div class="card-header d-flex">
            {#if escritura}
                <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Guardar</button>
            {/if}
            <div class="m-auto"></div>
            <Link to="/personas" class="btn btn-outline-secondary">Volver</Link>
        </div>
        <div class="card-body">
            <h4 class="h4 mb-3">Datos de la persona</h4>
            <div class={escritura ? "" : "disabled"}>
                <FormPersona bind:form={form} {es_nuevo} />
            </div>
        </div>
    </div>
</form>

<style>
    .disabled { pointer-events: none !important; }
</style>