<x-layout title="Lauck - Stock">
    
    <x-section-header subtitle="Gestión de Inventario" title="Listado de " highlight="Productos" />



    <div class="w-full flex flex-col xl:flex-row justify-between items-start xl:items-center gap-4 mb-6">
        
        <div class="w-full xl:w-4/5 flex flex-col md:flex-row gap-3">
            <div class="relative w-full md:w-2/5">
                <div class="absolute inset-y-0 start-0 flex items-center ps-3 pointer-events-none">
                    <svg class="w-4 h-4 text-gray-600 dark:text-gray-500" fill="none" viewBox="0 0 20 20"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m19 19-4-4m0-7A7 7 0 1 1 1 8a7 7 0 0 1 14 0Z"/></svg>
                </div>
                <input type="text" id="searchInput" class="block w-full p-3 ps-10 text-sm text-black dark:text-white border border-neutral-400 dark:border-neutral-700 rounded-lg bg-neutral-200 dark:bg-neutral-800 placeholder-gray-600 dark:placeholder-gray-500 focus:ring-neon-lime focus:border-neon-lime" placeholder="Buscar por nombre...">
            </div>

            <div class="w-full md:w-1/4">
                <select id="typeFilter" class="block w-full p-3 text-sm text-black dark:text-white border border-neutral-300 dark:border-neutral-700 rounded-lg bg-neutral-200 dark:bg-neutral-800 focus:ring-neon-lime focus:border-neon-lime cursor-pointer">
                    <option value="all">Todas las Categorías</option>
                    <option value="bike">Bicicletas</option>
                    <option value="clothing">Indumentaria</option>
                    <option value="accessory">Accesorios</option>
                    <option value="spare">Repuestos</option>
                    <option value="children">Infantil</option>
                    <option value="rollers">Rollers</option>
                    <option value="skate">Skate</option>
                    <option value="service">Servicios</option>
                    <option value="other">Otros</option>
                </select>
            </div>

            <div class="w-full md:w-1/4">
                <select id="stockFilter" class="block w-full p-3 text-sm text-black dark:text-white border border-neutral-300 dark:border-neutral-700 rounded-lg bg-neutral-200 dark:bg-neutral-800 focus:ring-neon-lime focus:border-neon-lime cursor-pointer">
                    <option value="all">Cualquier Stock</option>
                    <option value="low" class="text-red-600 dark:text-red-400 font-semibold">Stock en Alerta</option>
                    <option value="medium" class="text-yellow-600 dark:text-yellow-400 font-semibold">Stock Bajo</option>
                    <option value="ok" class="text-green-600 dark:text-green-400 font-semibold">Stock Normal</option>
                </select>
            </div>
        </div>

        <a href="{{ route('productos.create') }}" class="w-full xl:w-auto text-center px-5 py-3 text-sm font-bold text-neon-lime dark:text-neutral-900 bg-neutral-950 dark:bg-neon-lime rounded-lg hover:bg-neutral-900/80 hover:dark:bg-[#b3e600] transition-colors uppercase tracking-wide">
            + Nuevo Producto
        </a>
    </div>

    <div class="relative overflow-x-auto shadow-md sm:rounded-lg border border-gray-400 dark:border-neutral-800 w-full mb-4">
        <table class="w-full text-sm text-left rtl:text-right text-neutral-900 dark:text-white">
            <thead class="text-xs text-neutral-800 dark:text-gray-300 uppercase bg-gray-400 dark:bg-neutral-800 border-b border-gray-300 dark:border-neutral-700">
                <tr>
                    <th scope="col" class="px-6 py-3">
                        <div class="flex items-center gap-6">
                            <span class="w-40 shrink-0">Categoría</span>
                            <span>Detalle del Producto</span>
                        </div>
                    </th>
                    <th scope="col" class="px-6 py-3">Costo</th>
                    <th scope="col" class="px-6 py-3">Precio</th>
                    <th scope="col" class="px-6 py-3 text-center">Stock</th>
                    <th scope="col" class="px-6 py-3 text-right">Acciones</th>
                </tr>
            </thead>
            <tbody id="tabla-productos">
                @forelse($products as $product)
                <tr class="bg-gray-200/50 dark:bg-neutral-900/50 border-b border-gray-400 dark:border-neutral-800 hover:bg-gray-400 hover:dark:bg-neutral-800 transition-colors group product-row"
                    data-name="{{ strtolower($product->name) }}" 
                    data-type="{{ $product->type }}" 
                    data-stock="{{ $product->stock_quantity }}" 
                    data-min="{{ $product->min_stock_alert }}">
                    
                    <td class="px-6 py-4">
                        <div class="flex flex-col gap-1">
                            <div class="flex items-center gap-6">
                                <div class="text-sm font-bold tracking-wider shrink-0 w-40">
                                    @if($product->type === 'bike') <x-ui.badge color="neon">BICICLETA</x-ui.badge>
                                    @elseif($product->type === 'clothing') <x-ui.badge color="blue">INDUMENTARIA</x-ui.badge>
                                    @elseif($product->type === 'spare') <x-ui.badge color="gray">REPUESTO</x-ui.badge>
                                    @elseif($product->type === 'children') <x-ui.badge color="pink">INFANTIL</x-ui.badge>
                                    @elseif($product->type === 'rollers') <x-ui.badge color="purple">ROLLERS</x-ui.badge>
                                    @elseif($product->type === 'skate') <x-ui.badge color="orange">SKATE</x-ui.badge>
                                    @elseif($product->type === 'service') <x-ui.badge color="cyan">SERVICIO</x-ui.badge>
                                    @else <x-ui.badge color="yellow">ACCESORIO / OTRO</x-ui.badge> @endif
                                </div>
                                <div class="text-base font-semibold text-neutral-900 dark:text-white">
                                    {{ $product->name }}
                                </div>
                            </div>
                        </div>
                    </td>

                    <td class="px-6 py-4 font-mono text-base font-medium text-gray-600 dark:text-gray-400">
                        ${{ number_format($product->cost, 2) }}
                    </td>

                    <td class="px-6 py-4 font-mono text-base font-bold text-black dark:text-white">
                        ${{ number_format($product->price, 2) }}
                    </td>

                    <td class="px-6 py-4 text-center">
                        @if($product->stock_quantity <= $product->min_stock_alert)
                            <x-ui.badge color="red">{{ $product->stock_quantity }}</x-ui.badge>
                        @elseif($product->stock_quantity <= $product->min_stock_alert+5)
                            <x-ui.badge color="yellow">{{ $product->stock_quantity }}</x-ui.badge>
                        @else
                            <x-ui.badge color="green">{{ $product->stock_quantity }}</x-ui.badge>
                        @endif
                    </td>

                    <td class="px-6 py-4 text-right">
                        <div class="flex items-center gap-2 justify-end">
                            <a href="{{ route('productos.show', $product) }}" title="Ver Mas" class="font-semibold p-2 text-green-700 dark:text-green-400 border-2 border-green-700 rounded-lg hover:bg-green-700 dark:hover:bg-green-600 dark:hover:border-green-600 hover:text-white dark:hover:text-white transition-colors">
                                <svg class="size-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-width="2" d="M21 12c0 1.2-4.03 6-9 6s-9-4.8-9-6c0-1.2 4.03-6 9-6s9 4.8 9 6Z"/><path stroke="currentColor" stroke-width="2" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"/></svg>
                            </a>
                            <a href="{{ route('productos.edit', $product) }}" title="Editar" class="font-semibold p-2 text-blue-800 dark:text-blue-400 border-2 border-blue-800 rounded-lg hover:bg-blue-800 hover:text-white dark:hover:text-white transition-colors">
                                <svg class="size-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m14.304 4.844 2.852 2.852M7 7H4a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-4.5m2.409-9.91a2.017 2.017 0 0 1 0 2.853l-6.844 6.844L8 14l.713-3.565 6.844-6.844a2.015 2.015 0 0 1 2.852 0Z"/></svg>
                            </a>
                            <form action="{{route('productos.destroy',$product)}}" method="post" class="delete-form">
                                @csrf
                                @method('DELETE')
                                <button title="Eliminar" type="submit" class="w-full sm:w-auto p-2 font-bold dark:font-medium text-red-600 dark:text-red-400 border-2 border-red-600 rounded-lg hover:bg-red-600 hover:text-white dark:hover:text-white transition-colors">
                                    <svg class="size-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 7h14m-9 3v8m4-8v8M10 3h4a1 1 0 0 1 1 1v3H9V4a1 1 0 0 1 1-1ZM6 7h12v13a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V7Z"/></svg>
                                </button>
                           </form>
                        </div>
                    </td>
                </tr>
                @empty
                <tr>
                    <td colspan="5" class="px-6 py-10 text-center font-semibold text-gray-500">
                        No se encontraron productos en la base de datos.
                    </td>
                </tr>
                @endforelse
            </tbody>
        </table>
    </div>

    <div class="flex items-center justify-between px-4 py-3 bg-gray-200 dark:bg-neutral-900 border border-gray-400 dark:border-neutral-800 rounded-lg">
        <div class="text-sm text-gray-700 dark:text-gray-400 font-semibold" id="pagination-info">
            Cargando productos...
        </div>
        <div class="flex gap-2">
            <button id="btn-prev" class="px-4 py-2 text-sm font-bold text-gray-700 dark:text-gray-300 bg-white dark:bg-neutral-800 border border-gray-400 dark:border-neutral-600 rounded-lg hover:bg-gray-100 dark:hover:bg-neutral-700 transition-colors">
                Anterior
            </button>
            <button id="btn-next" class="px-4 py-2 text-sm font-bold text-gray-700 dark:text-gray-300 bg-white dark:bg-neutral-800 border border-gray-400 dark:border-neutral-600 rounded-lg hover:bg-gray-100 dark:hover:bg-neutral-700 transition-colors">
                Siguiente
            </button>
        </div>
    </div>
    
    <script>
        const searchInput = document.getElementById('searchInput');
        const typeFilter = document.getElementById('typeFilter');
        const stockFilter = document.getElementById('stockFilter');
        const rows = Array.from(document.querySelectorAll('.product-row'));
        
        const paginationInfo = document.getElementById('pagination-info');
        const btnPrev = document.getElementById('btn-prev');
        const btnNext = document.getElementById('btn-next');

        // Configuración de la paginación
        let currentPage = 1;
        const itemsPerPage = 10; // Cambiá este número si querés mostrar 15 o 20 por página
        let filteredRows = [...rows]; // Al principio, todas las filas están "filtradas"

        function aplicarFiltros() {
            const term = searchInput.value.toLowerCase();
            const type = typeFilter.value;
            const stock = stockFilter.value;

            // Guardamos en un array nuevo solo las filas que cumplen las condiciones
            filteredRows = rows.filter(row => {
                const name = row.dataset.name;
                const rowType = row.dataset.type;
                const qty = parseInt(row.dataset.stock);
                const min = parseInt(row.dataset.min);

                if (term !== '' && !name.includes(term)) return false;
                if (type !== 'all' && rowType !== type) return false;
                if (stock === 'low' && qty > min) return false;
                if (stock === 'medium' && (qty <= min || qty > min + 5)) return false;
                if (stock === 'ok' && qty <= min + 5) return false;

                return true;
            });

            // Siempre que filtramos, volvemos a la página 1
            currentPage = 1;
            renderPage();
        }

        function renderPage() {
            // 1. Ocultamos todas las filas por las dudas
            rows.forEach(row => row.style.display = 'none');

            // 2. Calculamos qué filas mostrar según la página
            const start = (currentPage - 1) * itemsPerPage;
            const end = start + itemsPerPage;
            const rowsToShow = filteredRows.slice(start, end);

            // 3. Mostramos solo las que tocan
            rowsToShow.forEach(row => row.style.display = '');

            // 4. Actualizamos los textos y botones
            const totalPages = Math.ceil(filteredRows.length / itemsPerPage) || 1;
            paginationInfo.innerText = `Página ${currentPage} de ${totalPages} (${filteredRows.length} resultados)`;

            // Habilitar/Deshabilitar botones
            btnPrev.disabled = currentPage === 1;
            btnNext.disabled = currentPage === totalPages;
            
            // Le damos estilo de "bloqueado" a los botones cuando corresponda
            btnPrev.classList.toggle('opacity-50', btnPrev.disabled);
            btnPrev.classList.toggle('cursor-not-allowed', btnPrev.disabled);
            btnNext.classList.toggle('opacity-50', btnNext.disabled);
            btnNext.classList.toggle('cursor-not-allowed', btnNext.disabled);
        }

        function changePage(delta) {
            const totalPages = Math.ceil(filteredRows.length / itemsPerPage) || 1;
            const newPage = currentPage + delta;
            
            if (newPage >= 1 && newPage <= totalPages) {
                currentPage = newPage;
                renderPage();
            }
        }

        if(searchInput) {
            searchInput.addEventListener('input', aplicarFiltros);
            typeFilter.addEventListener('change', aplicarFiltros);
            stockFilter.addEventListener('change', aplicarFiltros);
            
            btnPrev.addEventListener('click', () => changePage(-1));
            btnNext.addEventListener('click', () => changePage(1));
            
            // Inicializar la tabla apenas carga la página
            renderPage();
        }
    </script>
</x-layout>