<x-layout title="Lauck - Armar Pedido">
    <x-section-header subtitle="Proveedores" title="Armar Pedido: " highlight="{{ $supplier->name }}" />

    <div class="w-full max-w-5xl mx-auto bg-gray-200 dark:bg-panel-bg border border-neutral-400 dark:border-neutral-800 rounded-xl p-8 shadow-lg relative">
        
        <div class="mb-6 flex justify-between items-end">
            <div>
                <h3 class="text-xl font-bold text-neutral-900 dark:text-white">Seleccioná los productos</h3>
                <p class="text-sm text-gray-600 dark:text-gray-400">Teléfono registrado: {{ $supplier->phone ?? 'Ninguno' }}</p>
            </div>
            <a href="{{ route('suppliers.index') }}" class="text-sm font-bold text-gray-500 hover:text-white transition-colors">Volver al listado</a>
        </div>

        @if($products->isEmpty())
            <div class="bg-yellow-900/30 border border-yellow-600 text-yellow-500 p-4 rounded-lg">
                Este proveedor todavía no tiene productos asociados en el sistema.
            </div>
        @else
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4 bg-gray-300 dark:bg-neutral-800 p-4 rounded-lg border border-gray-400 dark:border-neutral-700">
                <div class="relative">
                    <div class="absolute inset-y-0 start-0 flex items-center ps-3 pointer-events-none">
                        <svg class="w-4 h-4 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-2.5 ps-10 text-sm text-black dark:text-white border border-gray-400 dark:border-neutral-600 rounded-lg bg-white dark:bg-neutral-900 focus:ring-neon-lime focus:border-neon-lime" placeholder="Buscar por nombre...">
                </div>

                <div>
                    <select id="typeFilter" class="block w-full p-2.5 text-sm text-black dark:text-white border border-gray-400 dark:border-neutral-600 rounded-lg bg-white dark:bg-neutral-900 focus:ring-neon-lime focus:border-neon-lime">
                        <option value="all">Todas las categorías</option>
                        <option value="bike">Bicicletas</option>
                        <option value="accessory">Accesorios</option>
                        <option value="clothing">Indumentaria</option>
                        <option value="spare">Repuestos</option>
                        <option value="children">Infantil</option>
                        <option value="rollers">Rollers</option>
                        <option value="skate">Skate</option>
                        <option value="other">Otros</option>
                    </select>
                </div>

                <div>
                    <select id="stockFilter" class="block w-full p-2.5 text-sm text-black dark:text-white border border-gray-400 dark:border-neutral-600 rounded-lg bg-white dark:bg-neutral-900 focus:ring-neon-lime focus:border-neon-lime">
                        <option value="all">Todo el inventario</option>
                        <option value="low">Solo Bajo Stock (Alerta)</option>
                    </select>
                </div>
            </div>

            <div class="relative overflow-x-auto overflow-y-auto max-h-[450px] border border-gray-400 dark:border-neutral-700 rounded-lg mb-6 custom-scrollbar">
                <table class="w-full text-sm text-left text-neutral-900 dark:text-gray-300">
                    <thead class="text-xs uppercase bg-gray-400 dark:bg-neutral-800 border-b border-gray-400 dark:border-neutral-700 sticky top-0 z-10">
                        <tr>
                            <th class="px-4 py-3 text-center w-16">Pedir</th>
                            <th class="px-4 py-3 w-24">Cantidad</th>
                            <th class="px-4 py-3">Producto</th>
                            <th class="px-4 py-3 text-center">Stock Actual</th>
                        </tr>
                    </thead>
                    <tbody id="tabla-productos">
                        @foreach($products as $product)
                            <tr class="border-b border-gray-300 dark:border-neutral-800 hover:bg-gray-300/50 dark:hover:bg-neutral-800/50 transition-colors 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-4 py-3 text-center">
                                    <input type="checkbox" class="product-check w-5 h-5 text-neon-lime bg-gray-100 border-gray-400 rounded focus:ring-neon-lime dark:focus:ring-neon-lime dark:ring-offset-gray-800 focus:ring-2 dark:bg-neutral-700 dark:border-neutral-600 cursor-pointer">
                                </td>
                                <td class="px-4 py-3">
                                    <input type="number" min="1" value="1" class="product-qty bg-white dark:bg-neutral-900 border border-gray-400 dark:border-neutral-600 text-sm rounded-lg focus:ring-neon-lime focus:border-neon-lime block w-full p-2 text-center disabled:opacity-50" disabled>
                                </td>
                                <td class="px-4 py-3 font-semibold product-name">
                                    {{ $product->name }}
                                </td>
                                <td class="px-4 py-3 text-center">
                                    @if($product->stock_quantity <= $product->min_stock_alert)
                                        <span class="px-2 py-1 rounded text-xs font-bold bg-red-200 text-red-800 dark:bg-red-900/50 dark:text-red-400">
                                            {{ $product->stock_quantity }} (¡Bajo!)
                                        </span>
                                    @else
                                        <span class="px-2 py-1 rounded text-xs font-bold bg-gray-300 text-gray-700 dark:bg-gray-800 dark:text-gray-400">
                                            {{ $product->stock_quantity }}
                                        </span>
                                    @endif
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>

            <div class="flex justify-end pt-4 border-t border-gray-400 dark:border-neutral-700 mt-4">
                <button onclick="enviarPedido()" class="flex items-center gap-2 px-6 py-3 bg-green-600 text-white font-bold rounded-lg hover:bg-green-500 transition-colors shadow-lg shadow-green-900/20">
                    <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><path fill-rule="evenodd" d="M12 4a8 8 0 0 0-6.895 12.06l.569 1.167-1.076 2.872 3.018-1.045 1.18.528A8 8 0 1 0 12 4Zm5.1 10.3c-.28-.14-1.65-.815-1.905-.909-.255-.094-.44-.14-.625.14-.185.28-.72 1.054-.882 1.265-.162.21-.324.234-.604.094-.28-.14-1.178-.435-2.246-1.385-.83-.739-1.39-1.65-1.552-1.93-.162-.28-.017-.432.123-.57.126-.125.28-.328.42-.493.14-.165.187-.28.28-.468.093-.188.047-.35-.023-.491-.07-.14-.625-1.508-.857-2.064-.225-.544-.454-.47-.625-.478-.162-.008-.348-.01-.533-.01-.185 0-.485.07-.74.35-.255.28-.972.95-.972 2.316 0 1.366.995 2.687 1.133 2.874.138.188 1.956 2.986 4.74 4.153.662.277 1.18.442 1.583.565.665.204 1.27.175 1.745.106.531-.077 1.65-.674 1.882-1.325.232-.651.232-1.21.162-1.325-.07-.116-.255-.186-.535-.326Z" clip-rule="evenodd"/></svg>
                    Armar Pedido por WhatsApp
                </button>
            </div>
        @endif

    </div>

    <style>
        .custom-scrollbar::-webkit-scrollbar { width: 8px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background-color: #4b5563; border-radius: 20px; }
    </style>

    <script>
        const searchInput = document.getElementById('searchInput');
        const typeFilter = document.getElementById('typeFilter');
        const stockFilter = document.getElementById('stockFilter');
        const rows = document.querySelectorAll('.product-row');

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

            rows.forEach(row => {
                const name = row.dataset.name;
                const rowType = row.dataset.type;
                const qty = parseInt(row.dataset.stock);
                const min = parseInt(row.dataset.min);

                let show = true;

                // filtrar por texto
                if (term !== '' && !name.includes(term)) show = false;
                
                // filtrar por categoría
                if (type !== 'all' && rowType !== type) show = false;
                
                // filtrar por stock
                if (stock === 'low' && qty > min) show = false;

                // ocultar o mostrar fila
                row.style.display = show ? '' : 'none';
            });
        }

        if(searchInput) {
            searchInput.addEventListener('input', aplicarFiltros);
            typeFilter.addEventListener('change', aplicarFiltros);
            stockFilter.addEventListener('change', aplicarFiltros);
        }

        // logica de habilitar/deshabilitar cant
        document.querySelectorAll('.product-check').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const tr = this.closest('tr');
                const qtyInput = tr.querySelector('.product-qty');
                qtyInput.disabled = !this.checked;
                
                if(this.checked) {
                    qtyInput.focus();
                    qtyInput.select();
                }
            });
        });

        // enviar a wsp 
        function enviarPedido() {
            let telefonoRaw = "{{ $supplier->phone }}";
            let telefono = telefonoRaw.replace(/\D/g, ''); 
            
            if (!telefono) {
                alert('Oops! El proveedor no tiene un número de teléfono guardado. Editalo primero en la pestaña de Proveedores.');
                return;
            }

            if (telefono.length === 10) {
                telefono = '549' + telefono; 
            }

            let mensaje = `Hola *{{ $supplier->name }}*, me comunico de Bicicletería Lauck para realizar el siguiente pedido:\n\n`;
            let hayProductos = false;

            document.querySelectorAll('.product-row').forEach(row => {
                const isChecked = row.querySelector('.product-check').checked;
                const qty = row.querySelector('.product-qty').value;
                const name = row.querySelector('.product-name').innerText.trim();

                if (isChecked && qty > 0) {
                    mensaje += `- ${qty}x ${name}\n`;
                    hayProductos = true;
                }
            });

            if (!hayProductos) {
                alert('Por favor, tildá al menos un producto para hacer el pedido.');
                return;
            }

            mensaje += `\n¡Muchas gracias!`;

            const url = `https://wa.me/${telefono}?text=${encodeURIComponent(mensaje)}`;
            window.open(url, '_blank');
        }
    </script>
</x-layout>