<x-app-layout>
    <x-slot name="title">
        <div class="d-flex align-items-center gap-2">
            <a href="{{ route('picking.index') }}" class="btn btn-sm btn-light rounded-circle shadow-sm border-0 me-2" title="Volver">
                <i class="bi bi-arrow-left text-secondary"></i>
            </a>
            <span class="text-secondary fw-normal">Picking de Almacén a Cocina / </span> Detalles #{{ str_pad($picking->id, 5, '0', STR_PAD_LEFT) }}
        </div>
    </x-slot>

    <!-- Picking Detail -->
    <div class="card mb-5 border-0 shadow rounded-4 bg-white overflow-hidden mt-2">
        <div class="card-header bg-primary bg-opacity-10 border-bottom-0 p-4">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h4 class="fw-bold text-primary mb-1">
                        Picking #{{ str_pad($picking->id, 5, '0', STR_PAD_LEFT) }}
                    </h4>
                    <div class="text-muted small">
                        Planificado para cocina el <span class="fw-bold">{{ \Carbon\Carbon::parse($picking->programacion->fecha)->format('d/m/Y') }}</span>
                    </div>
                </div>
                <div class="col-md-6 text-md-end mt-3 mt-md-0 d-flex justify-content-md-end align-items-center gap-4 text-start">
                    @if(isset($faltantes) && count($faltantes) > 0)
                        <button type="button" class="btn btn-warning bg-warning bg-opacity-10 text-warning-emphasis border-warning border-opacity-25 rounded-pill fw-bold shadow-sm px-3" data-bs-toggle="modal" data-bs-target="#faltantesModal" title="El stock actual no cubre lo solicitado.">
                            <i class="bi bi-lightning-fill me-1"></i> Auto Pre-compra <span class="badge bg-warning text-dark ms-1">{{ count($faltantes) }}</span>
                        </button>
                    @endif
                    <div class="d-inline-block text-end">
                        <div class="small fw-bold text-muted mb-1">Progreso General del Picking</div>
                        <div class="d-flex align-items-center gap-3">
                            <div class="progress" style="width: 200px; height: 12px; border-radius: 6px;">
                                <div class="progress-bar {{ $picking->porcentaje_completado == 100 ? 'bg-success' : 'bg-primary' }}" role="progressbar" style="width: {{ $picking->porcentaje_completado }}%;" aria-valuenow="{{ $picking->porcentaje_completado }}" aria-valuemin="0" aria-valuemax="100"></div>
                            </div>
                            <span class="fw-bold fs-5 {{ $picking->porcentaje_completado == 100 ? 'text-success' : 'text-primary' }}">{{ $picking->porcentaje_completado }}%</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="bg-light border-top border-bottom">
                        <tr>
                            <th class="ps-4 py-3" style="width: 40px;">
                                <div class="form-check m-0 d-flex align-items-center justify-content-center">
                                    <input class="form-check-input border-secondary shadow-sm" type="checkbox" id="selectAllCb" title="Seleccionar todos los faltantes" style="cursor:pointer">
                                </div>
                            </th>
                            <th class="ps-2 text-muted small py-3" style="width: 50px;">Estado</th>
                            <th class="text-muted small py-3">Insumo / Métrica</th>
                            <th class="text-center text-muted small py-3" style="width: 150px;">Solicitado</th>
                            <th class="text-center text-muted small py-3" style="width: 150px;">Despachado Real</th>
                            <th class="pe-4 text-end text-muted small py-3" style="width: 150px;">Acción de Almacén</th>
                        </tr>
                    </thead>
                    <tbody class="border-top-0">
                        @foreach($picking->items as $item)
                            <tr class="{{ $item->completado ? 'bg-light' : '' }}">
                                <td class="ps-4 text-center">
                                    @if(!$item->completado)
                                        <div class="form-check m-0 d-flex align-items-center justify-content-center">
                                            <input class="form-check-input border-secondary shadow-sm bulk-cb" type="checkbox" value="{{ $item->id }}" style="cursor:pointer">
                                        </div>
                                    @endif
                                </td>
                                <td class="ps-2 text-center">
                                    @if($item->completado)
                                        <i class="bi bi-check-circle-fill text-success fs-5"></i>
                                    @else
                                        <i class="bi bi-circle text-muted fs-5 opacity-50"></i>
                                    @endif
                                </td>
                                <td>
                                    <div class="fw-bold {{ $item->completado ? 'text-muted text-decoration-line-through' : 'text-dark' }}">
                                        {{ optional($item->insumo)->nombre ?? 'Insumo Eliminado' }}
                                    </div>
                                    <div class="small fw-normal text-secondary">{{ optional($item->insumo)->marca }}</div>
                                </td>
                                <td class="text-center fw-bold fs-6">
                                    {{ number_format($item->cantidad_necesaria, 2) }} <span class="text-muted fw-normal small">{{ $item->insumo->unidad_uso ?? 'Utd' }}</span>
                                </td>
                                <td class="text-center">
                                    @if($item->completado)
                                        <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 px-3 py-1 rounded-pill fw-bold">
                                            {{ number_format($item->cantidad_despachada, 2) }} {{ $item->insumo->unidad_uso ?? 'Utd' }}
                                        </span>
                                    @else
                                        <span class="badge bg-secondary bg-opacity-10 text-secondary border border-secondary border-opacity-10 px-3 py-1 rounded-pill fw-normal">Esperando...</span>
                                    @endif
                                </td>
                                <td class="pe-4 text-end">
                                    @can('completar.picking')
                                        @if($item->completado)
                                            <form action="{{ route('picking.deshacer', $item) }}" method="POST" class="d-inline" onsubmit="event.preventDefault(); confirmAction(this.querySelector('button'), '¿Está seguro de deshacer y devolver este ítem al almacén Kardex?');">
                                                @csrf
                                                @method('PATCH')
                                                <button type="submit" class="btn btn-sm btn-light text-danger border rounded-pill py-1">
                                                    <i class="bi bi-arrow-counterclockwise me-1"></i> Deshacer
                                                </button>
                                            </form>
                                        @else
                                            <button type="button" class="btn btn-sm btn-primary rounded-pill fw-bold shadow-sm py-1" data-bs-toggle="modal" data-bs-target="#completarItemModal{{ $item->id }}">
                                                <i class="bi bi-box-arrow-right me-1"></i> Despachar
                                            </button>

                                            <!-- Modal para Completar Item -->
                                            <div class="modal fade text-start" id="completarItemModal{{ $item->id }}" tabindex="-1" aria-hidden="true">
                                                <div class="modal-dialog modal-dialog-centered modal-sm">
                                                    <div class="modal-content border-0 shadow-lg rounded-4">
                                                        <div class="modal-header bg-light border-bottom-0 pb-0 rounded-top-4 pt-4 px-4">
                                                            <h6 class="modal-title fw-bold">Despachar Insumo</h6>
                                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                        </div>
                                                        <div class="modal-body p-4 text-center">
                                                            <form method="POST" action="{{ route('picking.completar', $item) }}">
                                                                @csrf
                                                                @method('PATCH')
                                                                
                                                                <div class="fs-5 fw-bold mb-1">{{ optional($item->insumo)->nombre }}</div>
                                                                <div class="text-muted small mb-4">Requerido: {{ number_format($item->cantidad_necesaria, 2) }} {{ $item->insumo->unidad_uso ?? 'Utd' }}</div>

                                                                <div class="mb-4 text-start">
                                                                    <label class="form-label fw-bold small text-muted">Manejo de Variación (Actual <span class="text-lowercase">{{ $item->insumo->unidad_uso ?? 'Utd' }}</span>):</label>
                                                                    <input type="number" class="form-control form-control-lg text-center fw-bold text-primary bg-primary bg-opacity-10 border-primary border-opacity-25" name="cantidad_despachada" required step="0.001" min="0.001" value="{{ $item->cantidad_necesaria }}">
                                                                    <div class="form-text small opacity-75"><i class="bi bi-info-circle me-1"></i> Edite la cantidad si entrega más o menos debido a formatos del almacén.</div>
                                                                </div>

                                                                <button type="submit" class="btn btn-success w-100 rounded-pill fw-bold pb-2 pt-2 shadow">
                                                                    <i class="bi bi-check2-circle me-1"></i> Confirmar Despacho
                                                                </button>
                                                            </form>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        @endif
                                    @endcan
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    @if(isset($faltantes) && count($faltantes) > 0)
    <!-- Modal Faltantes -->
    <div class="modal fade" id="faltantesModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content border-0 shadow-lg rounded-4">
                <div class="modal-header bg-warning bg-opacity-10 border-bottom-0 pb-0 rounded-top-4 pt-4 px-4">
                    <h5 class="modal-title fw-bold text-warning-emphasis">
                        <i class="bi bi-exclamation-triangle-fill me-2"></i> Insumos con Stock Insuficiente
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4 bg-light">
                    <p class="text-muted small mb-4">
                        Los siguientes insumos no pueden ser despachados porque su cantidad solicitada supera el saldo disponible actual en el almacén. Puede enviarlos a una Orden de Compra temporal (Pre-compra) con un solo clic.
                    </p>
                    
                    <form action="{{ route('picking.precompra', $picking) }}" method="POST">
                        @csrf
                        <div class="table-responsive bg-white rounded-3 shadow-sm border mb-4">
                            <table class="table table-hover align-middle mb-0">
                                <thead class="bg-light">
                                    <tr>
                                        <th class="ps-3 py-3 text-secondary small">Insumo</th>
                                        <th class="text-center text-secondary small py-3">Req. / Stock</th>
                                        <th class="text-end pe-3 text-secondary small py-3">A Comprar</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @php $indice = 0; @endphp
                                    @foreach($faltantes as $faltante)
                                        <tr>
                                            <td class="ps-3 py-3">
                                                <div class="fw-bold text-dark">{{ $faltante['nombre'] }}</div>
                                            </td>
                                            <td class="text-center py-3">
                                                <div class="small">
                                                    <span class="text-danger fw-bold">{{ number_format($faltante['cantidad_necesaria'], 2) }}</span> req.
                                                    <br>
                                                    <span class="text-success">{{ number_format($faltante['stock_actual'], 2) }}</span> disp.
                                                </div>
                                            </td>
                                            <td class="text-end pe-3 py-3">
                                                <div class="input-group input-group-sm w-75 float-end">
                                                    <input type="hidden" name="items[{{ $indice }}][insumo_id]" value="{{ $faltante['insumo_id'] }}">
                                                    <input type="number" name="items[{{ $indice }}][cantidad]" class="form-control text-end fw-bold" step="0.001" min="0.001" value="{{ $faltante['faltante'] }}" required>
                                                    <span class="input-group-text bg-light text-muted">{{ $faltante['unidad'] }}</span>
                                                </div>
                                            </td>
                                        </tr>
                                        @php $indice++; @endphp
                                    @endforeach
                                </tbody>
                            </table>
                        </div>

                        <div class="text-end">
                            <button type="button" class="btn btn-light rounded-pill border fw-bold px-4 me-2 shadow-sm" data-bs-dismiss="modal">Cerrar</button>
                            @can('crear.compras')
                                <button type="submit" class="btn btn-warning rounded-pill fw-bold shadow-sm px-4">
                                    <i class="bi bi-cart-plus me-1"></i> Generar Pre-compra
                                </button>
                            @else
                                <button type="button" class="btn btn-secondary rounded-pill fw-bold shadow-sm px-4" disabled title="No tienes permiso para crear órdenes de compra">
                                    <i class="bi bi-shield-lock me-1"></i> Sin Permiso de Compras
                                </button>
                            @endcan
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    @endif

    <!-- Formulario Oculto para POST Bloque -->
    <form id="formBulkDispatch" method="POST" action="{{ route('picking.completarBloque', $picking) }}">
        @csrf
        <!-- Bulk Dispatch Action Bar (Oculto por defecto envuelto en Form para capturar confirmAction) -->
        <div id="bulkActionBar" class="position-fixed bottom-0 start-50 translate-middle-x mb-4 shadow-lg rounded-pill bg-dark text-white d-none align-items-center justify-content-between px-4 py-3 border border-secondary border-opacity-50" style="z-index: 1050; min-width: 420px;">
            <div class="d-flex align-items-center me-4">
                <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center fw-bold me-3 shadow-sm" id="bulkCountBadge" style="width: 35px; height: 35px; font-size: 1.1rem;">
                    0
                </div>
                <span class="fw-medium">Ítems listos para despachar</span>
            </div>
            <button type="button" class="btn btn-primary rounded-pill fw-bold shadow-sm px-4" onclick="submitBulkDispatch(this)">
                <i class="bi bi-box-seam me-2"></i> Despachar Selección
            </button>
        </div>
    </form>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const selectAll = document.getElementById('selectAllCb');
            const checkboxes = document.querySelectorAll('.bulk-cb');
            const actionBar = document.getElementById('bulkActionBar');
            const countBadge = document.getElementById('bulkCountBadge');
            
            function updateBulkUI() {
                const checkedCount = document.querySelectorAll('.bulk-cb:checked').length;
                countBadge.textContent = checkedCount;
                
                if (checkedCount > 0) {
                    actionBar.classList.remove('d-none');
                    actionBar.classList.add('d-flex');
                } else {
                    actionBar.classList.remove('d-flex');
                    actionBar.classList.add('d-none');
                }
                
                if (selectAll) {
                    selectAll.checked = (checkedCount === checkboxes.length && checkboxes.length > 0);
                }
            }

            if (selectAll) {
                selectAll.addEventListener('change', function() {
                    checkboxes.forEach(cb => cb.checked = this.checked);
                    updateBulkUI();
                });
            }

            checkboxes.forEach(cb => {
                cb.addEventListener('change', updateBulkUI);
            });
        });

        function submitBulkDispatch(btnRef) {
            const form = document.getElementById('formBulkDispatch');
            const checked = document.querySelectorAll('.bulk-cb:checked');
            
            // Limpiar inputs viejos
            form.querySelectorAll('.hidden-item').forEach(el => el.remove());

            checked.forEach(cb => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'item_ids[]';
                input.value = cb.value;
                input.className = 'hidden-item';
                form.appendChild(input);
            });

            confirmAction(btnRef, `¿Despachar {{ $moneda }}{checked.length} insumos en bloque entregando la cantidad exacta solicitada al Kardex?`);
        }
    </script>
</x-app-layout>
