<div x-data="app" class="bg-white rounded-lg shadow">
    <div x-show="loading" class="fixed inset-0 bg-gray-800 bg-opacity-75 flex justify-center items-center z-50">
        <img src="../img/loading.gif" alt="Cargando..." class="w-16 h-16" />
    </div>

    <div class="container mx-auto p-6 w-full">
        <div class="justify-between items-center w-full md:flex">
            <div>
                <h1 class="text-2xl font-bold mb-2">Lista de proveedores</h1>
                <p class="mb-4 text-sm">Gestión de proveedores.</p>
            </div>

            <div class="mb-4 md:mb-0 relative">
                <input type="text" placeholder="Buscar..." class="border border-gray-300 rounded p-2 w-full"
                    x-model="search" @input.debounce.500ms="loadData()" />
            </div>

            <div class="flex items-center justify-end mb-4 gap-2 md:mb-0">
                <button @click="addModal = true"
                    class="bg-[#8eb02f] text-white px-4 py-2 rounded text-sm">Nuevo</button>
            </div>
        </div>

        <div class="overflow-x-auto">
            <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-3 border-b">Nombre</th>
                        <th class="py-2 px-3 border-b">Integraciones</th>
                        <th class="py-2 px-3 border-b"></th>
                    </tr>
                </thead>
                <tbody class="text-gray-500 select-none text-sm">
                    <template x-for="data in datos" :key="data.id">
                        <tr class="hover:bg-gray-100">
                            <td class="py-3 text-xs px-3 border-b" x-text="data.nombre"></td>
                            <td class="py-3 text-xs px-3 border-b">
                                <div class="flex flex-wrap gap-1">
                                    <template x-if="data.integraciones && data.integraciones.length > 0">
                                        <template x-for="integ in data.integraciones" :key="integ.id">
                                            <span class="bg-blue-100 text-blue-700 text-xs px-2 py-0.5 rounded-full" x-text="integ.title"></span>
                                        </template>
                                    </template>
                                    <template x-if="!data.integraciones || data.integraciones.length === 0">
                                        <span class="text-gray-400 italic">—</span>
                                    </template>
                                </div>
                            </td>
                            <td class="py-3 text-xs px-3 border-b w-24">
                                <div class="flex items-center gap-2">
                                    <button @click="openViewModal(data)" 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 @click="openEditModal(data)" 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 @click="openDeleteModal(data)" 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>
                                </div>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>

        <div class="flex justify-start items-center gap-2 p-4 text-sm">
            <button @click="page = Math.max(1, page - 1); loadData()" :disabled="page === 1"
                class="px-4 py-2 text-black bg-gray-200 rounded-l-md opacity-50 disabled:cursor-not-allowed">
                Anterior
            </button>
            <template x-for="pageNum in paginatedPages" :key="pageNum">
                <button @click="goToPage(pageNum)"
                    class="px-4 py-2 text-black bg-gray-200 bg-black text-gray-50 rounded-md hover:bg-gray-300"
                    :class="{ 'bg-black text-white': pageNum === page }" x-text="pageNum"></button>
            </template>
            <button @click="page += 1; loadData()" :disabled="datos.length < limit" :disabled="page === totalPages"
                class="px-4 py-2 text-black bg-gray-200 rounded-r-md opacity-50 disabled:cursor-not-allowed">
                Siguiente
            </button>
        </div>
    </div>

    <!-- Modal Ver -->
    <div x-show="viewModal"
        class="fixed inset-0 overflow-auto bg-gray-800 bg-opacity-75 flex justify-center items-center text-sm z-40">
        <div class="bg-white rounded-lg shadow-lg p-6 w-11/12 max-w-lg">
            <h2 class="text-xl font-bold mb-4">Ver proveedor</h2>

            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Nombre:</label>
                    <input type="text" x-model="selectedItem.nombre" disabled
                        class="border border-gray-300 rounded p-2 w-full" placeholder="Nombre" />
                </div>
            </div>

            <div class="mb-4">
                <label class="block mb-2 font-semibold">Integraciones relacionadas:</label>
                <div class="flex flex-wrap gap-2 min-h-8">
                    <template x-if="selectedItem.integraciones && selectedItem.integraciones.length > 0">
                        <template x-for="integ in selectedItem.integraciones" :key="integ.id">
                            <span class="bg-blue-100 text-blue-700 text-xs px-3 py-1 rounded-full" x-text="integ.title"></span>
                        </template>
                    </template>
                    <template x-if="!selectedItem.integraciones || selectedItem.integraciones.length === 0">
                        <span class="text-gray-400 text-xs italic">Sin integraciones relacionadas</span>
                    </template>
                </div>
            </div>

            <div class="flex justify-end gap-2 text-sm">
                <button @click="viewModal = false" class="px-4 py-2 bg-gray-600 text-white rounded">Cerrar</button>
            </div>
        </div>
    </div>

    <!-- Modal Editar -->
    <div x-show="editModal"
        class="fixed inset-0 overflow-auto bg-gray-800 bg-opacity-75 flex justify-center items-center text-sm z-40">
        <div class="bg-white rounded-lg shadow-lg p-6 w-11/12 max-w-lg">
            <h2 class="text-xl font-bold mb-4">Editar proveedor</h2>

            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Nombre:</label>
                    <input type="text" x-model="selectedItem.nombre" class="border border-gray-300 rounded p-2 w-full"
                        placeholder="Nombre" />
                </div>
            </div>

            <!-- Integraciones -->
            <div class="mb-4">
                <label class="block mb-2 font-semibold">Integraciones:</label>
                <div class="border border-gray-200 rounded p-3 max-h-48 overflow-y-auto">
                    <template x-if="submodules.length === 0">
                        <p class="text-gray-400 text-xs">Cargando...</p>
                    </template>
                    <template x-for="sub in submodules" :key="sub.id">
                        <label class="flex items-center gap-2 py-1 cursor-pointer hover:bg-gray-50 rounded px-1">
                            <input type="checkbox"
                                :value="sub.id"
                                :checked="isIntegSelected(sub.id)"
                                @change="toggleInteg(sub.id)"
                                class="rounded" />
                            <span class="text-sm" x-text="sub.title"></span>
                            <span class="text-xs text-gray-400" x-text="sub.url"></span>
                        </label>
                    </template>
                </div>
            </div>

            <div class="flex justify-between gap-2 text-sm">
                <button @click="updateItem()" class="px-4 py-2 bg-[#8eb02f] text-white rounded">Actualizar</button>
                <button @click="closeModals()" class="px-4 py-2 bg-gray-600 text-white rounded">Cerrar</button>
            </div>
        </div>
    </div>

    <!-- Modal Añadir -->
    <div x-show="addModal"
        class="fixed inset-0 overflow-auto bg-gray-800 bg-opacity-75 flex justify-center items-center text-sm z-40">
        <div class="bg-white rounded-lg shadow-lg p-6 w-11/12 max-w-lg">
            <h2 class="text-xl font-bold mb-4">Añadir proveedor</h2>

            <div class="flex flex-col sm:flex-row justify-between gap-4 mb-4">
                <div class="w-full">
                    <label class="block mb-2">Nombre:</label>
                    <input type="text" x-model="selectedItem.nombre" class="border border-gray-300 rounded p-2 w-full"
                        placeholder="Nombre" />
                </div>
            </div>

            <div class="flex justify-between gap-2 text-sm">
                <button @click="addItem()" class="px-4 py-2 bg-[#8eb02f] text-white rounded">Guardar</button>
                <button @click="addModal = false" class="px-4 py-2 bg-gray-600 text-white rounded">Cancelar</button>
            </div>
        </div>
    </div>

    <!-- Modal Eliminar -->
    <div x-show="deleteModal"
        class="fixed inset-0 overflow-auto bg-gray-800 bg-opacity-75 flex justify-center items-center z-40">
        <div class="bg-white rounded-lg shadow-lg p-6 w-11/12 max-w-lg text-sm">
            <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="flex mt-4 justify-end gap-2 text-sm">
                <button @click="deleteItem()" class="px-4 py-2 bg-red-500 text-white rounded">Eliminar</button>
                <button @click="closeModals()" class="bg-gray-600 text-white px-4 py-2 rounded">Cancelar</button>
            </div>
        </div>
    </div>
</div>

<script>
    function app() {
        return {
            datos: [],
            submodules: [],
            selectedIntegIds: [],
            loading: false,
            limit: 10,
            page: 1,
            search: '',
            totalPages: 0,
            paginatedPages: [],
            viewModal: false,
            addModal: false,
            editModal: false,
            deleteModal: false,
            selectedItem: {},
            errors: {},
            init() {
                this.loadData();
                this.loadSubmodules();
            },
            loadData() {
                if (this.search !== '') {
                    this.page = 1;
                    this.limit = 100;
                } else {
                    this.limit = 10;
                }
                this.setLoading(true);
                axios.get('/app/loadprovservidor', {
                    params: { page: this.page, limit: this.limit, search: this.search }
                }).then(response => {
                    this.datos = response.data.registros.map(data => ({
                        id: data.ID,
                        nombre: data.nombre,
                        integraciones: (data.integraciones || []).map(s => ({
                            id: s.ID,
                            title: s.title,
                            url: s.url,
                        })),
                    }));
                    this.totalPages = response.data.totalPages;
                    this.calculatePaginatedPages();
                }).catch(error => {
                    console.error('Error al obtener datos:', error);
                }).finally(() => {
                    this.setLoading(false);
                });
            },
            loadSubmodules() {
                axios.get('/app/loadsubmodules', { params: { limit: 200, page: 1 } })
                    .then(response => {
                        this.submodules = (response.data.registros || response.data.submodules || []).map(s => ({
                            id: s.ID,
                            title: s.title,
                            url: s.url,
                        }));
                    })
                    .catch(err => console.error('Error cargando submodules:', err));
            },
            isIntegSelected(id) {
                return this.selectedIntegIds.includes(id);
            },
            toggleInteg(id) {
                const idx = this.selectedIntegIds.indexOf(id);
                if (idx >= 0) {
                    this.selectedIntegIds.splice(idx, 1);
                } else {
                    this.selectedIntegIds.push(id);
                }
            },
            setSelectedItem(data) {
                this.selectedItem = { ...data };
                this.selectedIntegIds = (data.integraciones || []).map(i => i.id);
                this.errors = {};
            },
            resetSelectedItem() {
                this.selectedItem = {};
                this.selectedIntegIds = [];
                this.errors = {};
            },
            calculatePaginatedPages() {
                const maxVisiblePages = 5;
                const startPage = Math.max(1, this.page - Math.floor(maxVisiblePages / 2));
                const endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);
                this.paginatedPages = Array.from({ length: endPage - startPage + 1 }, (_, i) => i + startPage);
            },
            goToPage(page) {
                this.page = page;
                this.loadData();
            },
            setLoading(value) {
                this.loading = value;
            },
            openViewModal(data) {
                this.setSelectedItem(data);
                this.viewModal = true;
            },
            openEditModal(data) {
                this.setSelectedItem(data);
                this.editModal = true;
            },
            deleteItem() {
                this.setLoading(true);
                axios.delete(`/app/provservidor/${this.selectedItem.id}`)
                    .then(() => {
                        alert("Registro eliminado exitosamente.");
                        this.resetSelectedItem();
                        this.deleteModal = false;
                        this.loadData();
                    })
                    .catch(error => console.error("Error al eliminar el registro:", error))
                    .finally(() => this.setLoading(false));
            },
            openDeleteModal(data) {
                this.selectedItem.id = data.id;
                this.deleteModal = true;
            },
            closeModals() {
                this.viewModal = false;
                this.addModal = false;
                this.editModal = false;
                this.deleteModal = false;
                this.resetSelectedItem();
            },
            addItem() {
                this.setLoading(true);
                axios.post('/app/provservidor', this.selectedItem)
                    .then(response => {
                        alert("Proveedor añadido exitosamente.");
                        this.resetSelectedItem();
                        this.addModal = false;
                        this.loadData();
                    })
                    .catch(error => {
                        console.error("Error al añadir el proveedor:", error);
                    })
                    .finally(() => {
                        this.setLoading(false);
                    });
            },
            updateItem() {
                this.setLoading(true);
                const id = this.selectedItem.id;
                // Actualizar nombre
                axios.put(`/app/provservidor/${id}`, { nombre: this.selectedItem.nombre })
                    .then(() => {
                        // Sincronizar integraciones
                        return axios.put(`/app/provservidor/${id}/integraciones`, {
                            submodule_ids: this.selectedIntegIds
                        });
                    })
                    .then(() => {
                        alert("Proveedor actualizado exitosamente.");
                        this.resetSelectedItem();
                        this.editModal = false;
                        this.loadData();
                    })
                    .catch(error => {
                        console.error("Error al actualizar el proveedor:", error);
                    })
                    .finally(() => {
                        this.setLoading(false);
                    });
            }
        }
    }
</script>
