@extends('layouts.app')

@section('title', 'Inventario de almacen')

@push('styles')
    <link rel="stylesheet" href="{{ asset('css/crud-custom.css') }}">
    <link rel="stylesheet" href="{{ asset('css/almacen-inventario.css') }}">
@endpush

@section('content')
    @php
        $formatUnits = static function ($quantity, $unit): string {
            $value = is_numeric($quantity) ? (int) $quantity : 0;
            $suffix = trim((string) ($unit ?? ''));

            return trim($value . ' ' . $suffix);
        };

        $formatOnlyUnits = static function ($quantity): string {
            $value = is_numeric($quantity) ? (int) $quantity : 0;

            return trim($value . ' UNIDADES');
        };

        $formatLocation = static function ($shelf, $row): string {
            $parts = array_filter([
                filled($shelf) ? 'Estante ' . $shelf : null,
                filled($row) ? 'Fila ' . $row : null,
            ]);

            return $parts !== [] ? implode(' / ', $parts) : 'Sin ubicacion';
        };
    @endphp

    <div class="inventory-shell">
        <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-2 mb-3">
            <h1 class="h3 mb-0">Inventario de almacen</h1>
            <div class="d-flex gap-2">
                <a href="{{ route('almacen.index') }}" class="btn btn-outline-secondary">Volver a almacen</a>
            </div>
        </div>

        <div class="inventory-summary mb-3">
            <div class="inventory-stat">
                <div class="inventory-stat-label">Items listados</div>
                <div class="inventory-stat-value">{{ number_format((int) ($summary['items'] ?? 0)) }}</div>
            </div>
            <div class="inventory-stat">
                <div class="inventory-stat-label">Almacenado</div>
                <div class="inventory-stat-value">{{ number_format((int) ($summary['almacenado'] ?? 0)) }}</div>
            </div>
            <div class="inventory-stat">
                <div class="inventory-stat-label">En stock</div>
                <div class="inventory-stat-value">{{ number_format((int) ($summary['stock'] ?? 0)) }}</div>
            </div>
            <div class="inventory-stat">
                <div class="inventory-stat-label">Entregado</div>
                <div class="inventory-stat-value">{{ number_format((int) ($summary['entregado'] ?? 0)) }}</div>
            </div>
        </div>

        <form class="crud-card mb-3" method="GET" action="{{ route('almacen.inventario') }}">
            <div class="card-body p-3 d-flex flex-column flex-md-row gap-2 align-items-md-center">
                <div class="input-group">
                    <input
                        id="inventorySearchInput"
                        type="text"
                        class="form-control"
                        name="q"
                        value="{{ $search ?? '' }}"
                        placeholder="Buscar por SAP, codigo, descripcion, tipo o ubicacion"
                    >
                </div>
                <select class="form-select inventory-filter-select" name="items" aria-label="Filtrar items del inventario">
                    <option value="todos" @selected(($itemFilter ?? 'todos') === 'todos')>Todos los items</option>
                    <option value="almacenados" @selected(($itemFilter ?? 'todos') === 'almacenados')>Solo almacenados</option>
                    <option value="stock" @selected(($itemFilter ?? 'todos') === 'stock')>Solo en stock</option>
                    <option value="ambos" @selected(($itemFilter ?? 'todos') === 'ambos')>Almacenados y en stock</option>
                </select>
                <div class="d-flex gap-2">
                    <button class="btn btn-brand" type="submit">Buscar</button>
                    <a class="btn btn-outline-secondary" href="{{ route('almacen.inventario') }}">Limpiar</a>
                </div>
            </div>
        </form>

        @if (filled($search ?? ''))
            <p class="text-muted small mb-3">Buscando por: '{{ $search }}'</p>
        @endif

        @if (($itemFilter ?? 'todos') !== 'todos')
            <p class="text-muted small mb-3">Filtro aplicado: {{ match ($itemFilter) {
                'almacenados' => 'solo items almacenados',
                'stock' => 'solo items en stock',
                'ambos' => 'items almacenados y en stock',
                default => 'todos los items',
            } }}</p>
        @endif

        <div class="crud-card p-3">
            @if (method_exists($rows, 'links'))
                <div class="mb-2">
                    {{ $rows->links() }}
                </div>
            @endif

            <div class="crud-table-wrap">
                <table class="table table-sm align-middle mb-0 inventory-table w-100" style="table-layout: auto;">
                    <thead>
                        <tr>
                            <th>SAP</th>
                            <th>Codigo</th>
                            <th>Descripcion</th>
                            <th>Tipo</th>
                            <th>Almacenado</th>
                            <th>En stock</th>
                            <th>Entregado</th>
                            <th>Ubicacion</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody class="inventory-tbody-responsive">
                        @forelse ($rows as $row)
                            @php
                                $tipoNombre = $row->tipoInsumo->nombre ?? 'Sin tipo';
                                $tipoMarca = collect([$tipoNombre, $row->marca])->filter(fn ($value) => filled($value))->implode(' / ');
                                $almacenado = $formatUnits($row->cantidadUnidad, $row->unidad);
                                $stock = $formatOnlyUnits($row->cantidadUnidadUtil);
                                $entregado = $formatOnlyUnits($row->cantidadEntregada);
                                $ubicacion = $formatLocation($row->ubicacionEstante, $row->ubicacionFila);
                            @endphp
                            <tr>
                                <td>{{ $row->sap ?: '-' }}</td>
                                <td><span class="inventory-code">{{ $row->codigo }}</span></td>
                                <td>{{ $row->descripcion }}</td>
                                <td>{{ $tipoNombre }}</td>
                                <td><span class="inventory-qty">{{ $almacenado }}</span></td>
                                <td><span class="inventory-qty">{{ $stock }}</span></td>
                                <td>{{ $entregado }}</td>
                                <td><span class="inventory-location">{{ $ubicacion }}</span></td>
                                <td class="text-nowrap">
                                    <div class="actions-cell">
                                        <button
                                            class="btn btn-sm action-icon-btn inventory-detail-btn"
                                            type="button"
                                            title="Ver detalle"
                                            data-bs-toggle="modal"
                                            data-bs-target="#inventoryDetailModal"
                                            data-sap="{{ $row->sap ?: '-' }}"
                                            data-codigo="{{ $row->codigo }}"
                                            data-descripcion="{{ $row->descripcion }}"
                                            data-tipo="{{ $tipoNombre }}"
                                            data-almacenado="{{ $almacenado }}"
                                            data-stock="{{ $stock }}"
                                            data-entregado="{{ $entregado }}"
                                            data-ubicacion="{{ $ubicacion }}"
                                            aria-label="Ver detalle"
                                        >👁</button>
                                        <button
                                            class="btn btn-sm action-icon-btn inventory-edit-btn"
                                            type="button"
                                            title="Editar"
                                            data-bs-toggle="modal"
                                            data-bs-target="#inventoryEditModal"
                                            data-update-url="{{ route('almacen.inventario.update', ['id' => $row->id]) }}"
                                            data-item-id="{{ $row->id }}"
                                            data-sap="{{ $row->sap ?: '-' }}"
                                            data-codigo="{{ $row->codigo }}"
                                            data-descripcion="{{ $row->descripcion }}"
                                            data-tipo="{{ $tipoNombre }}"
                                            data-marca="{{ $row->marca ?? '' }}"
                                            data-unidad-almacenado="{{ $row->unidad ?? '' }}"
                                            data-unidad-stock="{{ $row->unidadUtil ?? '' }}"
                                            data-cantidad-almacenada="{{ (int) ($row->cantidadUnidad ?? 0) }}"
                                            data-cantidad-stock="{{ (int) ($row->cantidadUnidadUtil ?? 0) }}"
                                            data-cantidad-entregada="{{ (int) ($row->cantidadEntregada ?? 0) }}"
                                            aria-label="Editar"
                                        >✏️</button>
                                        <form method="POST" class="d-inline" action="{{ route('almacen.inventario.destroy', ['id' => $row->id]) }}" onsubmit="return confirm('Eliminar item del inventario? Esta accion pondra las cantidades en cero.');">
                                            @csrf
                                            @method('DELETE')
                                            <button class="btn btn-sm action-icon-btn inventory-danger-btn" type="submit" title="Eliminar" aria-label="Eliminar">🚫</button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="9" class="text-center py-4 text-muted">No hay items con cantidades registradas para mostrar.</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div
        class="modal fade crud-modal"
        id="inventoryEditModal"
        tabindex="-1"
        aria-hidden="true"
        data-auto-open="{{ old('__inventory_action') === 'edit' && $errors->any() ? 'true' : 'false' }}"
    >
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <form
                    id="inventoryEditForm"
                    method="POST"
                    action="{{ route('almacen.inventario.update', ['id' => old('inventory_item_id', 0)]) }}"
                >
                    @csrf
                    @method('PUT')
                    <input type="hidden" name="__inventory_action" value="edit">
                    <input type="hidden" id="inventory_item_id" name="inventory_item_id" value="{{ old('inventory_item_id') }}">

                    <div class="modal-header">
                        <h2 class="modal-title fs-5" id="inventoryEditModalTitle">Editar item de inventario</h2>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                    </div>
                    <div class="modal-body">
                        @if (old('__inventory_action') === 'edit' && $errors->any())
                            <div class="alert alert-danger" role="alert">
                                <div class="fw-semibold mb-1">Hay errores de validacion:</div>
                                <ul class="mb-0 ps-3">
                                    @foreach ($errors->all() as $error)
                                        <li>{{ $error }}</li>
                                    @endforeach
                                </ul>
                            </div>
                        @endif

                        <div class="inventory-edit-grid">
                            <div class="modal-field">
                                <label class="form-label" for="edit_codigo_display">Codigo</label>
                                <input class="form-control inventory-readonly-field" id="edit_codigo_display" name="codigo_display" type="text" value="{{ old('codigo_display') }}" readonly>
                            </div>
                            <div class="modal-field">
                                <label class="form-label" for="edit_tipo_marca_display">Tipo / Marca</label>
                                <input class="form-control inventory-readonly-field" id="edit_tipo_marca_display" name="tipo_marca_display" type="text" value="{{ old('tipo_marca_display') }}" readonly>
                            </div>
                            <div class="modal-field full">
                                <label class="form-label" for="edit_descripcion_display">Descripcion</label>
                                <input class="form-control inventory-readonly-field" id="edit_descripcion_display" name="descripcion_display" type="text" value="{{ old('descripcion_display') }}" readonly>
                            </div>
                            
                            <div class="modal-field">
                                <label class="form-label" for="cantidad_almacenada">Cantidad almacenada</label>
                                <input class="form-control @if (old('__inventory_action') === 'edit' && $errors->has('cantidad_almacenada')) is-invalid @endif" id="cantidad_almacenada" name="cantidad_almacenada" type="number" min="0" step="1" value="{{ old('cantidad_almacenada') }}" required>
                            </div>
                            <div class="modal-field">
                                <label class="form-label" for="cantidad_stock">Cantidad en stock</label>
                                <input class="form-control @if (old('__inventory_action') === 'edit' && $errors->has('cantidad_stock')) is-invalid @endif" id="cantidad_stock" name="cantidad_stock" type="number" min="0" step="1" value="{{ old('cantidad_stock') }}" required>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancelar</button>
                        <button class="btn btn-brand" type="submit">Guardar cambios</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade crud-modal" id="inventoryDetailModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="modal-title fs-5">Detalle del item</h2>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <div class="detail-grid">
                        <div class="detail-card">
                            <div class="detail-label">SAP</div>
                            <div class="detail-value" id="detail_sap">-</div>
                        </div>
                        <div class="detail-card">
                            <div class="detail-label">Codigo</div>
                            <div class="detail-value" id="detail_codigo">-</div>
                        </div>
                        <div class="detail-card full">
                            <div class="detail-label">Descripcion</div>
                            <div class="detail-value" id="detail_descripcion">-</div>
                        </div>
                        <div class="detail-card">
                            <div class="detail-label">Tipo</div>
                            <div class="detail-value" id="detail_tipo">-</div>
                        </div>
                        <div class="detail-card">
                            <div class="detail-label">Ubicacion</div>
                            <div class="detail-value" id="detail_ubicacion">-</div>
                        </div>
                        <div class="detail-card">
                            <div class="detail-label">Almacenado</div>
                            <div class="detail-value" id="detail_almacenado">-</div>
                        </div>
                        <div class="detail-card">
                            <div class="detail-label">En stock</div>
                            <div class="detail-value" id="detail_stock">-</div>
                        </div>
                        <div class="detail-card full">
                            <div class="detail-label">Entregado</div>
                            <div class="detail-value" id="detail_entregado">-</div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cerrar</button>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const inventoryEditModalElement = document.getElementById('inventoryEditModal');
            const inventoryEditForm = document.getElementById('inventoryEditForm');
            const inventoryEditModal = inventoryEditModalElement ? new bootstrap.Modal(inventoryEditModalElement) : null;
            const detailTargets = {
                sap: document.getElementById('detail_sap'),
                codigo: document.getElementById('detail_codigo'),
                descripcion: document.getElementById('detail_descripcion'),
                tipo: document.getElementById('detail_tipo'),
                ubicacion: document.getElementById('detail_ubicacion'),
                almacenado: document.getElementById('detail_almacenado'),
                stock: document.getElementById('detail_stock'),
                entregado: document.getElementById('detail_entregado'),
            };

            const editTargets = {
                itemId: document.getElementById('inventory_item_id'),
                codigo: document.getElementById('edit_codigo_display'),
                tipoMarca: document.getElementById('edit_tipo_marca_display'),
                descripcion: document.getElementById('edit_descripcion_display'),
                almacenada: document.getElementById('cantidad_almacenada'),
                stock: document.getElementById('cantidad_stock'),
                entregada: document.getElementById('cantidad_entregada'),
            };

            const populateEditForm = (button) => {
                if (!button || !inventoryEditForm) {
                    return;
                }

                const tipoValue = String(button.dataset.tipo || '').trim();
                const marcaValue = String(button.dataset.marca || '').trim();
                const tipoMarcaValue = [tipoValue, marcaValue].filter((value) => value !== '').join(' / ');

                inventoryEditForm.action = button.dataset.updateUrl || inventoryEditForm.action;
                editTargets.itemId.value = button.dataset.itemId || '';
                editTargets.codigo.value = button.dataset.codigo || '-';
                editTargets.tipoMarca.value = tipoMarcaValue || tipoValue || '-';
                editTargets.descripcion.value = button.dataset.descripcion || '-';
                editTargets.almacenada.value = button.dataset.cantidadAlmacenada || '0';
                editTargets.stock.value = button.dataset.cantidadStock || '0';
                if (editTargets.entregada) {
                    editTargets.entregada.value = button.dataset.cantidadEntregada || '0';
                }
            };

            document.querySelectorAll('.inventory-detail-btn').forEach((button) => {
                button.addEventListener('click', () => {
                    detailTargets.sap.textContent = button.dataset.sap || '-';
                    detailTargets.codigo.textContent = button.dataset.codigo || '-';
                    detailTargets.descripcion.textContent = button.dataset.descripcion || '-';
                    detailTargets.tipo.textContent = button.dataset.tipo || '-';
                    detailTargets.ubicacion.textContent = button.dataset.ubicacion || '-';
                    detailTargets.almacenado.textContent = button.dataset.almacenado || '-';
                    detailTargets.stock.textContent = button.dataset.stock || '-';
                    detailTargets.entregado.textContent = button.dataset.entregado || '-';
                });
            });

            document.querySelectorAll('.inventory-edit-btn').forEach((button) => {
                button.addEventListener('click', () => {
                    populateEditForm(button);
                });
            });

            if (inventoryEditModalElement?.dataset.autoOpen === 'true' && inventoryEditModal) {
                inventoryEditModal.show();
            }
        });
    </script>
@endpush