<x-app-layout>
    <x-slot name="title">
        Almacén — Stock de Sucursal
    </x-slot>

    <!-- Resumen Widgets -->
    <div class="row g-3 mb-4">
        <div class="col-md-4">
            <div class="card border-0 shadow-sm rounded-4 h-100">
                <div class="card-body p-4 d-flex align-items-center">
                    <div class="rounded-circle bg-primary bg-opacity-10 d-flex align-items-center justify-content-center me-3" style="width: 48px; height: 48px;">
                        <i class="bi bi-box-seam-fill text-primary fs-4"></i>
                    </div>
                    <div>
                        <div class="text-muted small fw-bold text-uppercase">Insumos Registrados</div>
                        <div class="fs-4 fw-bold text-dark">{{ $resumen['total'] }}</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card border-0 shadow-sm rounded-4 h-100">
                <div class="card-body p-4 d-flex align-items-center">
                    <div class="rounded-circle bg-warning bg-opacity-10 d-flex align-items-center justify-content-center me-3" style="width: 48px; height: 48px;">
                        <i class="bi bi-exclamation-triangle-fill text-warning fs-4"></i>
                    </div>
                    <div>
                        <div class="text-muted small fw-bold text-uppercase">En Alerta (Stock Bajo)</div>
                        <div class="fs-4 fw-bold text-warning">{{ $resumen['alerta'] }}</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card border-0 shadow-sm rounded-4 h-100">
                <div class="card-body p-4 d-flex align-items-center">
                    <div class="rounded-circle bg-danger bg-opacity-10 d-flex align-items-center justify-content-center me-3" style="width: 48px; height: 48px;">
                        <i class="bi bi-x-circle-fill text-danger fs-4"></i>
                    </div>
                    <div>
                        <div class="text-muted small fw-bold text-uppercase">Sin Stock</div>
                        <div class="fs-4 fw-bold text-danger">{{ $resumen['sinStock'] }}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filtros y Acciones -->
    <div class="card mb-4 border-0 shadow-sm rounded-4">
        <div class="card-body p-4">
            <div class="row g-3 align-items-center justify-content-between">
                <div class="col-md-8">
                    <form method="GET" action="{{ route('almacen.index') }}" class="d-flex flex-wrap gap-2">
                        <input type="text" name="search" value="{{ request('search') }}" placeholder="Buscar insumo por nombre..." class="form-control" style="max-width: 280px;">

                        <select name="estado" class="form-select tom-select" style="max-width: 200px;">
                            <option value="">Todos los niveles</option>
                            <option value="alerta" {{ request('estado') === 'alerta' ? 'selected' : '' }}>Stock Bajo / Alerta</option>
                            <option value="sin_stock" {{ request('estado') === 'sin_stock' ? 'selected' : '' }}>Sin Stock (0)</option>
                        </select>

                        <button type="submit" class="btn btn-outline-secondary rounded-pill">
                            <i class="bi bi-funnel-fill"></i> Filtrar
                        </button>

                        @if(request()->hasAny(['search', 'estado']))
                            <a href="{{ route('almacen.index') }}" class="btn btn-light rounded-pill border">Limpiar</a>
                        @endif
                    </form>
                </div>
                <div class="col-md-5 text-md-end mt-3 mt-md-0 d-flex justify-content-md-end gap-2 flex-wrap">
                    @if(isset($faltantes) && count($faltantes) > 0)
                        <button type="button" class="btn btn-warning rounded-pill fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#autoReqModal" style="white-space: nowrap;">
                            <i class="bi bi-lightning-charge-fill text-dark me-1"></i> Auto Pre-req <span class="badge bg-light text-dark ms-1">{{ count($faltantes) }}</span>
                        </button>
                    @endif

                    <a href="{{ route('almacen.kardex') }}" class="btn btn-outline-dark rounded-pill fw-bold shadow-sm" style="white-space: nowrap;">
                        <i class="bi bi-journal-text me-1"></i> Ver Kardex
                    </a>
                    <button type="button" class="btn btn-primary rounded-pill fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#ajusteStockModal" style="white-space: nowrap;">
                        <i class="bi bi-plus-slash-minus me-1"></i> Ajuste
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabla de Stock -->
    <div class="card border-0 shadow-sm rounded-4">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th class="ps-4 py-3 text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Insumo</th>
                            <th class="py-3 text-end text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Stock Actual</th>
                            <th class="py-3 text-end text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Mínimo</th>
                            <th class="py-3 text-center text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Estado</th>
                            <th class="pe-4 py-3 text-end text-secondary text-uppercase" style="font-size: 0.75rem; font-weight: 700;">Acciones</th>
                        </tr>
                    </thead>
                    <tbody class="border-top-0">
                        @forelse ($stocks as $stock)
                            @php
                                $alerta = $stock->cantidad_actual < $stock->cantidad_minima;
                                $sinStock = $stock->cantidad_actual == 0;
                            @endphp
                            <tr>
                                <td class="ps-4 py-3">
                                    <div class="d-flex align-items-center">
                                        <div class="rounded-circle d-flex align-items-center justify-content-center border me-3 {{ $sinStock ? 'bg-danger bg-opacity-10' : ($alerta ? 'bg-warning bg-opacity-10' : 'bg-light') }}" style="width: 40px; height: 40px;">
                                            <i class="bi bi-box-seam {{ $sinStock ? 'text-danger' : ($alerta ? 'text-warning' : 'text-secondary') }} fs-5"></i>
                                        </div>
                                        <div>
                                            <div class="fw-bold text-dark">{{ $stock->insumo->nombre }}</div>
                                            <div class="text-muted small">{{ $stock->insumo->unidad_uso }}</div>
                                        </div>
                                    </div>
                                </td>
                                <td class="py-3 text-end">
                                    <span class="badge rounded-pill px-3 py-2 {{ $sinStock ? 'bg-danger bg-opacity-10 text-danger' : ($alerta ? 'bg-warning bg-opacity-10 text-warning' : 'bg-success bg-opacity-10 text-success') }}">
                                        {{ number_format($stock->cantidad_actual, 2) }}
                                    </span>
                                </td>
                                <td class="py-3 text-end text-muted fw-semibold">
                                    {{ number_format($stock->cantidad_minima, 2) }}
                                </td>
                                <td class="py-3 text-center">
                                    @if($sinStock)
                                        <span class="badge bg-danger bg-opacity-10 text-danger rounded-pill px-2">Sin Stock</span>
                                    @elseif($alerta)
                                        <span class="badge bg-warning bg-opacity-10 text-warning rounded-pill px-2">Bajo Mínimo</span>
                                    @else
                                        <span class="badge bg-success bg-opacity-10 text-success rounded-pill px-2">Normal</span>
                                    @endif
                                </td>
                                <td class="pe-4 py-3 text-end">
                                    <a href="{{ route('insumos.show', $stock->insumo) }}" class="btn btn-sm btn-light border rounded-circle" title="Ver detalle del insumo">
                                        <i class="bi bi-eye text-primary"></i>
                                    </a>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="5" class="text-center py-5 text-muted">
                                    <i class="bi bi-archive fs-1 d-block mb-3 text-light"></i>
                                    No hay registros de stock en esta sucursal.
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            @if($stocks->hasPages())
                <div class="p-3 border-top">
                    {{ $stocks->links('pagination::bootstrap-5') }}
                </div>
            @endif
        </div>
    </div>

    <!-- Modal Ajuste Manual de Stock -->
    <div class="modal fade" id="ajusteStockModal" tabindex="-1" aria-labelledby="ajusteStockLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <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">
                    <h5 class="modal-title fw-bold" id="ajusteStockLabel"><i class="bi bi-plus-slash-minus text-primary me-2"></i> Ajuste Manual de Stock</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4">
                    <form method="POST" action="{{ route('almacen.ajuste') }}">
                        @csrf
                        <div class="row g-3">
                            <div class="col-12">
                                <label class="form-label fw-bold small text-muted">Insumo <span class="text-danger">*</span></label>
                                <select name="insumo_id" class="form-select tom-select" required>
                                    <option value="">Seleccionar insumo...</option>
                                    @foreach($stocks as $st)
                                        <option value="{{ $st->insumo_id }}">{{ $st->insumo->nombre }} (actual: {{ number_format($st->cantidad_actual, 2) }})</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold small text-muted">Tipo <span class="text-danger">*</span></label>
                                <select name="tipo" class="form-select tom-select" required>
                                    <option value="entrada">Entrada (+)</option>
                                    <option value="salida">Salida (-)</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold small text-muted">Cantidad <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" name="cantidad" step="0.001" min="0.001" placeholder="0.000" required>
                            </div>
                            <div class="col-12">
                                <label class="form-label fw-bold small text-muted">Motivo <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="motivo" placeholder="ej. Merma por vencimiento, Conteo físico, etc." minlength="5" maxlength="200" required>
                            </div>
                        </div>

                        <div class="mt-4 pt-3 border-top text-end">
                            <button type="button" class="btn btn-light rounded-pill border fw-bold px-4 me-2 shadow-sm" data-bs-dismiss="modal">Cancelar</button>
                            <button type="submit" class="btn btn-primary rounded-pill fw-bold shadow-sm px-4">
                                <i class="bi bi-check-lg me-1"></i> Registrar Ajuste
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    @if(isset($faltantes) && count($faltantes) > 0)
    <!-- Modal Auto Pre-Requerimiento -->
    <div class="modal fade" id="autoReqModal" 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 Bajo Nivel Mínimo
                    </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 han caído por debajo de su stock mínimo de seguridad. Puede enviarlos a un Requerimiento (Pre-compra) para abastecer el almacén con un solo clic. Edite las cantidades recomendadas si fuera necesario.
                    </p>
                    
                    <form action="{{ route('almacen.auto_req') }}" 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">Actual / Mínimo</th>
                                        <th class="text-end pe-3 text-secondary small py-3">A Pedir</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['stock_actual'], 2) }}</span> act.
                                                    <br>
                                                    <span class="text-success">{{ number_format($faltante['stock_minimo'], 2) }}</span> min.
                                                </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['reorden'] }}" 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">Cancelar</button>
                            <button type="submit" class="btn btn-warning rounded-pill fw-bold shadow-sm px-4">
                                <i class="bi bi-lightning-charge-fill me-1"></i> Generar Requerimiento
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    @endif
</x-app-layout>
