<!-- Container Principal -->
<div x-data="modals" @keydown.escape="closeModal"   class="bg-white rounded-lg shadow">
    <div class="container mx-auto p-6 w-full ">
        <h1 class="text-2xl font-bold mb-4">Lista de Submodulos</h1>
        <div class="justify-between w-full  md:flex">
            <p class="mb-4 text-sm">Gestión de Submodulos.</p>
            <!-- Campo de Búsqueda -->
            <div class="mb-4 relative">
                <input type="text" x-model="searchQuery" placeholder="Buscar..."
                    class="border border-gray-300 rounded w-full md:w-60 p-2 text-sm" @input="loadModules()">

                <!-- Contenedor para el botón o el ícono de carga -->
                <div x-show="isLoading" class="absolute right-2 top-2 flex items-center">
                    <!-- SVG de cargando (puedes reemplazarlo con un botón si lo prefieres) -->
                    <svg class="animate-spin h-5 w-5 text-gray-500" xmlns="http://www.w3.org/2000/svg" fill="none"
                        viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4">
                        </circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
                    </svg>
                </div>
            </div>
            <!-- Botón Nuevo Módulo -->
            <div class="flex justify-end mb-4">
                <button class="bg-[#8eb02f] text-white px-4 py-2 rounded text-sm"
                    x-on:click="addModal=true">Nuevo</button>
            </div>

        </div>

        <!-- Agregar el GIF de carga -->
        <div x-show="loading" class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-50 justify-center items-center">
            <img src="../img/loading.gif" alt="Cargando..." class="w-16 h-16" />
        </div>
        <div class="overflow-x-auto max-w-full">
            <!-- Tabla de Módulos -->
            <table class=" table-auto w-full">
                <thead class="text-sm  text-left py-4  border-b border-gray-300">
                    <tr class="text-left font-semibold border-collapse">
                        <th class="py-2 px-4 border-b w-52 ">Título</th>
                        <th class="py-2 px-4 border-b">Descripción</th>
                        <th class="py-2 px-4 border-b w-52 ">URL</th>
                        <th class="py-2 px-4 border-b">Modulo</th>
                        <th class="py-2 px-4 border-b w-32"></th>
                    </tr>
                </thead>
                <tbody id="modulesList" class="text-gray-500 select-none text-sm ">
                    <!-- Mensaje de Carga Inicial -->
                    <tr class="hover:bg-gray-100">
                        <td colspan="" class="py-2 px-4 border-b text-center w-full">
                            <div class="text-center mx-auto justify-center flex space-x-2">
                                <!-- SVG de cargando (puedes reemplazarlo con un botón si lo prefieres) -->
                                <svg class="animate-spin h-5 w-5 mx-1 text-gray-500" xmlns="http://www.w3.org/2000/svg"
                                    fill="none" viewBox="0 0 24 24">
                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
                                        stroke-width="4">
                                    </circle>
                                    <path class="opacity-75" fill="currentColor"
                                        d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z">
                                    </path>
                                </svg>
                                Cargando registros...
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div>
            <!-- Los botones de paginación se generarán aquí -->
            <div id="pagination" class="flex justify-left my-4 text-sm">
            </div>
            <!-- Mostrar conteo de registros -->
            <div id="recordCountDiv" class="text-sm text-gray-700 ml-4">

            </div>
        </div>
    </div>

    <!-- Modal Ver -->
    <div x-cloak x-show="viewModal" x-transition
        class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-40 justify-center items-center text-sm">
        <div class="bg-white p-6 rounded shadow-lg max-w-sm w-full overflow-y-auto max-h-full">
            <h2 class="text-xl font-bold mb-2">Ver registro</h2>
            <p class="font-semibold" x-text="Title"></p>
            <p class="mt-2" x-text="Description"></p>
            <p class="mt-2" x-text="URL"></p>
            <p class="mt-2" x-text="ModuleTitle"></p>
            <button class="mt-4 bg-[#8eb02f] text-white px-4 py-2 rounded"
                x-on:click="viewModal = false">Cerrar</button>
        </div>
    </div>

    <!-- Modal Editar -->
    <div x-cloak x-show="editModal" x-transition
        class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-40 justify-center items-center text-sm">
        <div class="bg-white p-6 rounded shadow-lg max-w-sm w-full overflow-y-auto max-h-full">
            <h2 class="text-xl font-bold mb-2">Editar registro</h2>
            <form @submit.prevent="submitEditModule">
                <label class="block mb-2" for="editTitle">Título</label>
                <input type="text" id="editTitle" x-model="Title" placeholder="Título"
                    class="border border-gray-300 rounded w-full p-2" required>
                <label class="block mt-4 mb-2" for="editDescription">Descripción</label>
                <textarea id="editDescription" x-model="Description" placeholder="Descripción"
                    class="border border-gray-300 rounded w-full p-2" required></textarea>
                <label class="block mb-2" for="editURL">URL</label>
                <input type="text" id="editURL" x-model="URL" placeholder="URL"
                    class="border border-gray-300 rounded w-full p-2" required>
                <label class="block mt-4 mb-2" for="editRole">Modulo</label>
                <select id="editModule" x-model="ModuleTitle" class="border border-gray-300 rounded w-full p-2"
                    required>
                    <option value="" disabled selected>Selecciona un modulo</option> <!-- Opción predeterminada -->
                    <template x-for="module in modules" :key="module.ID">
                        <option :value="module.ID" x-text="module.title"></option>
                        <!-- Asegúrate de que 'name' y 'id' existen en tus roles -->
                    </template>
                </select>
                <div class="mt-4 flex justify-between">
                    <button type="submit" class="bg-[#8eb02f] text-white px-4 py-2 rounded">Guardar Cambios</button>
                    <button type="button" class="bg-gray-600 text-white px-4 py-2 rounded"
                        x-on:click="closeModal">Cancelar</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal Añadir -->
    <div x-cloak x-show="addModal" x-transition
        class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-40 justify-center items-center text-sm">
        <div class="bg-white p-6 rounded shadow-lg max-w-sm w-full overflow-y-auto max-h-full">
            <h2 class="text-xl font-bold mb-2">Agregar registro</h2>
            <form @submit.prevent="submitAddModule">
                <label class="block mb-2" for="title">Título</label>
                <input type="text" id="title" x-model="newTitle" placeholder="Título"
                    class="border border-gray-300 rounded w-full p-2" required>
                <label class="block mt-4 mb-2" for="description">Descripción</label>
                <textarea id="description" x-model="newDescription" placeholder="Descripción"
                    class="border border-gray-300 rounded w-full p-2" required></textarea>
                <label class="block mb-2" for="URL">URL</label>
                <input type="text" id="URL" x-model="newURL" placeholder="URL"
                    class="border border-gray-300 rounded w-full p-2" required>

                <label class="block mt-4 mb-2" for="editModule">Modulo</label>
                <select id="editModule" x-model="newModule" class="border border-gray-300 rounded w-full p-2" required>
                    <option value="" disabled selected>Selecciona un modulo</option> <!-- Opción predeterminada -->
                    <template x-for="module in modules" :key="module.ID">
                        <option :value="module.ID" x-text="module.title"></option>
                        <!-- Asegúrate de que 'name' y 'id' existen en tus roles -->
                    </template>
                </select>
                <div class="mt-4 flex justify-between">
                    <button type="submit" class="bg-[#8eb02f] text-white px-4 py-2 rounded">Guardar registro</button>
                    <button type="button" class="bg-gray-600 text-white px-4 py-2 rounded"
                        x-on:click="closeModal">Cancelar</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal Confirmar Eliminación -->
    <div x-cloak x-show="showConfirmModal" x-transition
        class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-40 justify-center items-center text-sm">
        <div class="bg-white p-6 rounded shadow-lg max-w-sm w-full overflow-y-auto max-h-full">
            <h2 class="text-xl font-bold mb-4">Confirmar Eliminación</h2>
            <p>¿Estás seguro de que deseas eliminar este registro?</p>
            <div class="mt-4 flex justify-end">
                <button @click="deleteModule()" class="bg-red-500 text-white px-4 py-2 rounded mr-2">Eliminar</button>
                <button @click="closeModal" class="bg-gray-600 text-white px-4 py-2 rounded">Cancelar</button>
            </div>
        </div>
    </div>

    <!-- Alpine.js Script -->
    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.data('modals', () => ({
                addModal: false,
                editModal: false,
                viewModal: false,
                showConfirmModal: false,

                newTitle: '',
                newDescription: '',
                newURL: '',
                newModule: '',

                Title: '',
                Description: '',
                URL: '',
                ModuleTitle: '',

                Id: null,
                deleteId: null,
                loading: false,
                totalRecords: 0, // Agregar esta línea
                isLoading: false,

                modules: '',


                init() {
                    this.loadModules();
                },
                //CARGAR MODULOS
                searchQuery: '', // Agrega esta línea dentro del objeto Alpine

                // Modifica la función loadModules para incluir la búsqueda
                loadModules(page = 1) {
                    this.isLoading = true;
                    //this.loading = true;
                    const search = this.searchQuery ? `&search=${this.searchQuery}` : '';
                    fetch(`/app/loadsubmodules?page=${page}${search}`)
                        .then(response => response.json())
                        .then(data => {
                            this.totalRecords = data.total; // Establece el total de registros aquí
                            this.modules = data.modules;
                            this.submodules = data.submodules; // Asignar módulos
                            this.totalPages = data.totalPages; // Asignar total de páginas
                            this.createPagination(this.totalPages, page);
                            const modulesList = document.getElementById('modulesList');
                            modulesList.innerHTML = ''; // Limpiar la lista actual
                            if (data.modules.length === 0) {
                                modulesList.innerHTML = `<tr><td colspan="3" class="py-2 px-4 border-b text-center">No hay módulos disponibles.</td></tr>`;
                            } else {
                                data.submodules.forEach(submodule => {
                                    const row = document.createElement('tr');
                                    row.setAttribute('data-module-id', submodule.ID);
                                    row.classList.add('hover:bg-gray-100')
                                    row.innerHTML = `
                                       <td class="py-3 text-xs px-4 border-b ">${submodule.title}</td>
                                        <td class="py-3 text-xs px-4 border-b ">${submodule.description}</td>
                                        <td class="py-3 text-xs px-4 border-b ">${submodule.url}</td>
                                        <td class="py-3 text-xs px-4 border-b ">${submodule.module.title}</td>
                                        <td class="py-3 text-xs px-4 border-b flex justify-between space-x-1">
                                            <button x-on:click="viewModal = true; Title = '${submodule.title}'; Description = '${submodule.description}'; ModuleTitle = '${submodule.module.title}'; URL = '${submodule.url}';" title="Ver">
                                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5 text-[#8eb02f]">
                                                    <path stroke-linecap="round" stroke-linejoin="round" d="M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z" />
                                                    <path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
                                                </svg>
                                            </button>
                                            <button x-on:click="editModal = true; Id = '${submodule.ID}'; Title = '${submodule.title}'; Description = '${submodule.description}'; ModuleTitle = '${submodule.module.ID}'; URL = '${submodule.url}';" title="Editar">
                                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5">
                                                    <path stroke-linecap="round" stroke-linejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10" />
                                                </svg>
                                            </button>
                                            <button x-on:click="showConfirmModal = true; deleteId = '${submodule.ID}';" title="Eliminar">
                                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5 text-red-500">
                                                    <path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" />
                                                </svg>
                                            </button>
                                        </td>

                                    `;
                                    modulesList.appendChild(row);
                                });

                                // Lógica de paginación
                                const totalPages = Math.ceil(this.totalRecords / data.limit);
                                this.createPagination(totalPages, page)
                            }
                        })
                        .catch(error => console.error('Error:', error))
                        .finally(() => {
                            this.isLoading = false; // Ocultar el GIF de carga
                        });
                },
                createPagination(totalPages, currentPage) {
                    const paginationContainer = document.getElementById('pagination');
                    paginationContainer.innerHTML = ''; // Limpiar la paginación actual

                    // Crear un contenedor para los botones de paginación
                    const paginationButtonsContainer = document.createElement('div');
                    paginationButtonsContainer.className = "md:flex mx-auto mb-2 md:justify-between items-center w-full"; // Alinear los botones

                    // Función para crear un botón
                    const createButton = (text, isDisabled, onClick, additionalClasses = '') => {
                        const button = document.createElement('button');
                        button.textContent = text;
                        button.disabled = isDisabled;
                        button.className = `px-4 py-2 text-black bg-gray-200 ${additionalClasses} ${isDisabled ? 'opacity-50 cursor-not-allowed' : 'hover:bg-gray-300'}`;
                        if (!isDisabled) {
                            button.onclick = onClick;
                        }
                        return button;
                    };

                    // Botones de paginación
                    const leftContainer = document.createElement('div');
                    leftContainer.className = "md:flex text-center mb-2"; // Contenedor para los botones de paginación a la izquierda
                    leftContainer.appendChild(createButton('Anterior', currentPage === 1, () => this.loadModules(currentPage - 1), 'rounded-l-md'));

                    for (let i = 1; i <= totalPages; i++) {
                        const pageButton = createButton(i, false, () => this.loadModules(i), `mx-1 ${i === currentPage ? 'bg-black text-gray-50' : 'bg-white text-black'} rounded-md`);
                        leftContainer.appendChild(pageButton);
                    }

                    leftContainer.appendChild(createButton('Siguiente', currentPage === totalPages, () => this.loadModules(currentPage + 1), 'rounded-r-md'));

                    paginationButtonsContainer.appendChild(leftContainer);

                    // Agregar el conteo de registros a la derecha
                    const recordCountDiv = document.createElement('div');
                    const startRecord = (currentPage - 1) * 10 + 1; // Primer registro de la página actual
                    const endRecord = Math.min(currentPage * 10, this.totalRecords); // Último registro mostrado
                    recordCountDiv.className = "text-sm text-gray-700 text-center md:ml-auto"; // Sin margen para alineación a la izquierda
                    recordCountDiv.innerHTML = `Mostrando ${startRecord} a ${endRecord} de ${this.totalRecords} registros`;

                    paginationButtonsContainer.appendChild(recordCountDiv);

                    // Agregar los botones de paginación al contenedor principal
                    paginationContainer.appendChild(paginationButtonsContainer);
                },

                //CERRAR MODALES
                closeModal() {
                    this.addModal = false;
                    this.editModal = false;
                    this.viewModal = false;
                    this.showConfirmModal = false;
                },
                //CREAR
                submitAddModule() {
                    this.loading = true;
                    fetch('/app/submodules', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            title: this.newTitle,
                            description: this.newDescription,
                            url: this.newURL,
                            module_id: parseInt(this.newModule)
                        })
                    })
                        .then(response => response.json())
                        .then(() => {
                            this.newTitle = '';
                            this.newDescription = '';
                            this.newURL = '';
                            this.newModule = '';
                            this.closeModal();
                            this.loadModules();
                        })
                        .catch(error => console.error('Error:', error))
                        .finally(() => {
                            this.loading = false; // Ocultar el GIF de carga
                        });
                },
                //ACTUALIZAR
                submitEditModule() {
                    this.loading = true;
                    fetch(`/app/submodules/${this.Id}`, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            title: this.Title,
                            description: this.Description,
                            url: this.URL,
                            module_id: parseInt(this.ModuleTitle),
                        })
                    })
                        .then(response => response.json())
                        .then(() => {
                            this.newTitle = '';
                            this.newDescription = '';
                            this.newURL = '';
                            this.newModule = '';
                            this.closeModal();
                            this.loadModules();
                        })
                        .catch(error => console.error('Error:', error))
                        .finally(() => {
                            this.loading = false; // Ocultar el GIF de carga
                        });
                },
                //ELIMINAR
                deleteModule() {
                    this.loading = true;
                    fetch(`/app/submodules/${this.deleteId}`, {
                        method: 'DELETE',
                        headers: { 'Content-Type': 'application/json' }
                    })
                        .then(() => {
                            this.closeModal();
                            this.loadModules();
                        })
                        .catch(error => console.error('Error:', error))
                        .finally(() => {
                            this.loading = false; // Ocultar el GIF de carga
                        });
                }
            }));
        });
    </script>
</div>