<script lang="ts">
    import { onMount } from "svelte";
    import type { PermisoDto } from "../types";

    let {
        permiso = $bindable(),
        onClose,
        onSubmit,
        modalTitle = "Modificar Permiso",
    }: {
        permiso: PermisoDto;
        onClose: (a: string) => void;
        onSubmit: (arg0: PermisoDto) => void;
        modalTitle: string;
    } = $props();

    const maxChars = $state(25);
    let remaining: number = $state(25);
    const ogdesc: string = permiso.descripcion;

    function saveChanges(e:Event) {
        e.preventDefault();
        onSubmit(permiso);
        onClose(ogdesc);
    }

    function updateRemaining(event: Event) {
        const inputValue = (event.target as HTMLInputElement).value;
        permiso.descripcion = inputValue;
        remaining = maxChars - inputValue.length;
    }

    $effect(() => {
        remaining = maxChars - permiso.descripcion.length;
    });
</script>

<div
    class="modal show fade d-block"
    tabindex="-1"
    aria-labelledby="textModalLabel"
    style="background-color: rgba(0, 0, 0, 0.3);"
>
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="textModalLabel">{modalTitle}</h5>
                <button
                    type="button"
                    class="btn-close"
                    aria-label="Close"
                    onclick={() => onClose(ogdesc)}
                ></button>
            </div>
            <form onsubmit={(e)=>saveChanges(e)}>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="textInput" class="form-label">Descripcion</label
                    >
                    <input
                        type="text"
                        class="form-control"
                        id="textInput"
                        value={permiso.descripcion}
                        maxlength={maxChars}
                        oninput={updateRemaining}
                    />
                    <small class="form-text text-muted">
                        {remaining} caracteres restantes de {maxChars}
                    </small>
                </div>
            </div>
            <div class="modal-footer">
                <button
                    type="button"
                    class="btn btn-secondary"
                    onclick={() => onClose(ogdesc)}>Cerrar</button
                >
                <button
                    type="submit"
                    class="btn btn-primary"
                    >Guardar</button
                >
            </div>
            </form>
        </div>
    </div>
</div>
