@extends('layouts.app')

@section('title', 'Devolucion')
@section('full_width', '1')

@push('styles')
    <style>
        .page-shell {
            display: grid;
            gap: 1rem;
        }

        .form-shell {
            display: grid;
            gap: 1rem;
        }

        .content-stage {
            width: min(1500px, 100%);
            margin: 0 auto;
            padding: 0 0.75rem;
        }

        .section-card {
            border: 1px solid #e4ebf2;
            border-radius: 16px;
            background: #ffffff;
            padding: 1rem 1.1rem;
            box-shadow: 0 8px 18px -18px rgba(0, 0, 0, 0.35);
            min-width: 0;
        }

        .section-title {
            font-size: 0.82rem;
            font-weight: 700;
            letter-spacing: 0.08em;
            text-transform: uppercase;
            color: #7E8080;
            margin-bottom: 0.8rem;
        }

        .section-title-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 0.75rem;
            margin-bottom: 0.8rem;
            flex-wrap: wrap;
        }

        .section-title-row .section-title {
            margin-bottom: 0;
        }

        .summary-bar {
            display: grid;
            grid-template-columns: repeat(1, minmax(0, 1fr));
            gap: 0.75rem;
        }

        .summary-item {
            border: 1px solid #e8eef4;
            border-radius: 12px;
            background: #f8fbfd;
            padding: 0.75rem 0.9rem;
            min-width: 0;
        }

        .summary-item .label {
            font-size: 0.76rem;
            color: #7E8080;
            margin-bottom: 0.2rem;
        }

        .summary-item .value {
            color: #446078;
            font-weight: 600;
            line-height: 1.25;
            overflow-wrap: anywhere;
            word-break: break-word;
        }

        .table-wrap {
            border: 1px solid #e8eef4;
            border-radius: 14px;
            overflow: hidden;
            background: #fff;
            min-width: 0;
        }

        .table-wrap table {
            margin-bottom: 0;
        }

        .items-table {
            min-width: 1180px;
        }

        .items-table td,
        .items-table th {
            padding: 0.55rem 0.65rem;
        }

        .table-wrap thead th {
            background: #f7fafc;
            border-bottom-color: #e8eef4;
            font-size: 0.82rem;
            color: #446078;
        }

        .table-wrap td,
        .table-wrap th {
            white-space: normal;
            overflow-wrap: anywhere;
            word-break: break-word;
            vertical-align: top;
        }

        .items-empty-cell {
            padding: 1.5rem 1rem !important;
            background: #fbfdff;
        }

        .items-empty-state {
            display: grid;
            gap: 0.25rem;
            justify-items: center;
            text-align: center;
            color: #7E8080;
        }

        .items-empty-state strong {
            color: #446078;
            font-size: 0.98rem;
            font-weight: 700;
        }

        .items-empty-state span {
            font-size: 0.88rem;
        }

        .action-btn {
            min-height: 40px;
            padding: 0.5rem 1rem;
            font-weight: 600;
        }

        .cantidad-input {
            width: 84px;
            min-width: 84px;
        }

        .checkbox-cell {
            text-align: center;
            vertical-align: middle;
        }

        .form-check-input {
            width: 1.05rem;
            height: 1.05rem;
            margin-top: 0;
            border-color: #aebfcc;
        }

        .form-check-input:checked {
            background-color: #077BA1;
            border-color: #077BA1;
        }

        .section-note {
            color: #7E8080;
            font-size: 0.9rem;
            margin: 0;
        }

        .operation-result {
            border-color: rgba(7, 123, 161, 0.25);
            background: linear-gradient(180deg, #f8fcff 0%, #ffffff 100%);
            color: #446078;
        }

        .operation-result strong,
        .operation-result .value {
            color: #077BA1;
        }

        .operation-result .table {
            color: #446078;
        }

        .operation-result .table thead th {
            background: #f2f9fd;
            color: #077BA1;
            border-bottom-color: #d9e8f2;
        }

        @media (min-width: 768px) {
            .summary-bar {
                grid-template-columns: repeat(4, minmax(0, 1fr));
            }
        }

        @media (min-width: 992px) and (max-aspect-ratio: 4/3) {
            .content-stage {
                width: min(1320px, 100%);
                padding: 0 0.5rem;
            }
        }
    </style>
@endpush

@section('content')
    @php
        $resultado = session('devolucion_resultado');
        $scope = $scope ?? 'prestamos';
        $processRoute = $processRoute ?? route('asignacion.devolucion.prestamos.procesar');
    @endphp
    <div class="content-stage">
        <div class="card card-soft border-0">
            <div class="card-body p-4 p-md-5">
                <h1 class="h4 mb-2">Devolucion de asignaciones</h1>

                <div class="d-flex flex-wrap gap-2 mb-3">
                    <a href="{{ route('asignacion.devolucion.prestamos') }}" class="btn btn-sm {{ $scope === 'prestamos' ? 'btn-brand' : 'btn-outline-secondary' }}">Devolucion de prestamos</a>
                    <a href="{{ route('asignacion.devolucion.transferencias') }}" class="btn btn-sm {{ $scope === 'transferencias' ? 'btn-brand' : 'btn-outline-secondary' }}">Devolucion de transferencias</a>
                </div>

                <div class="page-shell">
                    @if ($resultado)
                        <section class="section-card operation-result">
                            <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
                                <div class="section-title mb-0">Resultado de operacion</div>
                                <div class="d-flex gap-2">
                                    <a href="{{ $resultado['receipt_url'] ?? '#' }}" class="btn btn-outline-primary btn-sm {{ empty($resultado['receipt_url']) ? 'disabled' : '' }}">Ver comprobante</a>
                                    <a href="{{ $resultado['export_url'] ?? '#' }}" class="btn btn-success btn-sm {{ empty($resultado['export_url']) ? 'disabled' : '' }}">Exportar Excel (.xlsx)</a>
                                </div>
                            </div>
                            <div class="summary-bar mb-3">
                                <div class="summary-item">
                                    <div class="label">Devueltos</div>
                                    <div class="value">{{ $resultado['devueltos'] ?? 0 }}</div>
                                </div>
                                <div class="summary-item">
                                    <div class="label">Utilizados</div>
                                    <div class="value">{{ $resultado['utilizados'] ?? 0 }}</div>
                                </div>
                                <div class="summary-item">
                                    <div class="label">Omitidos</div>
                                    <div class="value">{{ $resultado['omitidos'] ?? 0 }}</div>
                                </div>
                                <div class="summary-item">
                                    <div class="label">Solicitante</div>
                                    <div class="value">{{ $prestamista }}</div>
                                </div>
                            </div>

                            @if (! empty($resultado['prestamos']))
                                <div class="section-title">Prestamos devueltos</div>
                                <div class="table-responsive mb-3">
                                    <table class="table table-sm align-middle mb-0">
                                        <thead>
                                            <tr>
                                                <th>Codigo</th>
                                                <th>Descripcion</th>
                                                <th>Cant.</th>
                                                <th>Tipo / Marca</th>
                                                <th>Ubicacion</th>
                                                <th>Stock antes</th>
                                                <th>Stock despues</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach ($resultado['prestamos'] as $row)
                                                <tr>
                                                    <td>{{ $row['codigo'] ?? '-' }}</td>
                                                    <td>{{ $row['descripcion'] ?? '-' }}</td>
                                                    <td>{{ $row['cantidad'] ?? 0 }}</td>
                                                    <td>{{ $row['tipo'] ?? '-' }}</td>
                                                    <td>{{ $row['ubicacion'] ?? '-' }}</td>
                                                    <td>{{ $row['stock_antes'] ?? 0 }}</td>
                                                    <td>{{ $row['stock_despues'] ?? 0 }}</td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            @endif

                            @if (! empty($resultado['transferencias']))
                                <div class="section-title">Transferencias devueltas</div>
                                <div class="table-responsive mb-3">
                                    <table class="table table-sm align-middle mb-0">
                                        <thead>
                                            <tr>
                                                <th>Codigo</th>
                                                <th>Descripcion</th>
                                                <th>Cant.</th>
                                                <th>Tipo / Marca</th>
                                                <th>Emisor</th>
                                                <th>Receptor</th>
                                                <th>Ubicacion</th>
                                                <th>Stock antes</th>
                                                <th>Stock despues</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach ($resultado['transferencias'] as $row)
                                                <tr>
                                                    <td>{{ $row['codigo'] ?? '-' }}</td>
                                                    <td>{{ $row['descripcion'] ?? '-' }}</td>
                                                    <td>{{ $row['cantidad'] ?? 0 }}</td>
                                                    <td>{{ $row['tipo'] ?? '-' }}</td>
                                                    <td>{{ $row['emisor'] ?? '-' }}</td>
                                                    <td>{{ $row['receptor'] ?? '-' }}</td>
                                                    <td>{{ $row['ubicacion'] ?? '-' }}</td>
                                                    <td>{{ $row['stock_antes'] ?? 0 }}</td>
                                                    <td>{{ $row['stock_despues'] ?? 0 }}</td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            @endif

                            @if (! empty($resultado['utilizados_items']))
                                <div class="section-title">Transferencias catalogadas como utilizadas</div>
                                <div class="table-responsive">
                                    <table class="table table-sm align-middle mb-0">
                                        <thead>
                                            <tr>
                                                <th>Codigo</th>
                                                <th>Descripcion</th>
                                                <th>Cant.</th>
                                                <th>Tipo / Marca</th>
                                                <th>Ubicacion</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach ($resultado['utilizados_items'] as $row)
                                                <tr>
                                                    <td>{{ $row['codigo'] ?? '-' }}</td>
                                                    <td>{{ $row['descripcion'] ?? '-' }}</td>
                                                    <td>{{ $row['cantidad'] ?? 0 }}</td>
                                                    <td>{{ $row['tipo'] ?? '-' }}</td>
                                                    <td>{{ $row['ubicacion'] ?? '-' }}</td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            @endif
                        </section>
                    @endif

                    <section class="section-card">
                        <div class="section-title">Solicitante</div>
                        <div class="summary-bar">
                            <div class="summary-item">
                                <div class="label">Prestamista (cedula validada)</div>
                                <div class="value">{{ $prestamista }}</div>
                            </div>
                            <div class="summary-item">
                                <div class="label">Nombre completo</div>
                                <div class="value">{{ $prestamistaUser->nombre ?? 'Sin nombre' }}</div>
                            </div>
                            <div class="summary-item">
                                <div class="label">Tipo de usuario</div>
                                <div class="value">{{ $tipoLabel }}</div>
                            </div>
                            <div class="summary-item">
                                <div class="label">Numero de dependencia</div>
                                <div class="value">{{ $prestamistaUser->dependencia ?? 'Sin dependencia' }}</div>
                            </div>
                        </div>
                    </section>

                    <form id="devolucion-form" method="POST" action="{{ $processRoute }}" class="form-shell">
                        @csrf

                        @if ($scope === 'prestamos')
                        <section class="section-card">
                            <div class="section-title-row">
                                <div class="section-title">Prestamos activos</div>
                                <p class="section-note mb-0">Solo se muestran prestamos de alimentos y utensilios.</p>
                            </div>
                            <div class="table-wrap">
                                <div class="table-responsive">
                                    <table class="table table-sm align-middle items-table">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Nro. Oper.</th>
                                                <th>Codigo</th>
                                                <th>Descripcion</th>
                                                <th>Cantidad activa</th>
                                                <th>Cantidad a devolver</th>
                                                <th>Tipo / Marca</th>
                                                <th>Fecha entrega</th>
                                                <th>Ubicacion</th>
                                                <th>Observacion</th>
                                                <th>Devolver</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @forelse ($prestamos as $index => $prestamo)
                                                <tr>
                                                    <td>{{ $index + 1 }}</td>
                                                    <td>{{ $prestamo['num_operacion'] }}</td>
                                                    <td>
                                                        {{ $prestamo['codigo'] }}
                                                        <input type="hidden" name="prestamos[{{ $index }}][id]" value="{{ $prestamo['id'] }}">
                                                    </td>
                                                    <td>{{ $prestamo['descripcion'] }}</td>
                                                    <td>{{ $prestamo['cantidad'] }}</td>
                                                    <td>
                                                        <input type="number" min="1" max="{{ $prestamo['cantidad'] }}" name="prestamos[{{ $index }}][cantidad]" class="form-control form-control-sm cantidad-input" value="{{ old("prestamos.$index.cantidad", $prestamo['cantidad']) }}">
                                                    </td>
                                                    <td>{{ $prestamo['tipo'] }}</td>
                                                    <td>{{ $prestamo['fecha_entrega'] }}</td>
                                                    <td>{{ $prestamo['ubicacion'] }}</td>
                                                    <td>{{ $prestamo['observacion'] ?: '-' }}</td>
                                                    <td class="checkbox-cell">
                                                        <input class="form-check-input" type="checkbox" name="prestamos[{{ $index }}][seleccionado]" value="1" {{ old("prestamos.$index.seleccionado") ? 'checked' : '' }}>
                                                    </td>
                                                </tr>
                                            @empty
                                                <tr>
                                                    <td colspan="11" class="items-empty-cell">
                                                        <div class="items-empty-state">
                                                            <strong>No hay prestamos activos para devolver</strong>
                                                            <span>Cuando existan equipos o herramientas prestados, apareceran en esta tabla.</span>
                                                        </div>
                                                    </td>
                                                </tr>
                                            @endforelse
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </section>
                        @endif

                        @if ($scope === 'transferencias')
                        <section class="section-card">
                            <div class="section-title-row">
                                <div class="section-title">Transferencias activas</div>
                                <p class="section-note mb-0">Puede devolver completamente, devolver parcialmente o catalogar como utilizado.</p>
                            </div>
                            <div class="table-wrap">
                                <div class="table-responsive">
                                    <table class="table table-sm align-middle items-table">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Nro. Oper.</th>
                                                <th>Codigo</th>
                                                <th>Descripcion</th>
                                                <th>Cantidad activa</th>
                                                <th>Cantidad a devolver</th>
                                                <th>Tipo / Marca</th>
                                                <th>Fecha entrega</th>
                                                <th>Emisor</th>
                                                <th>Receptor</th>
                                                <th>Ubicacion</th>
                                                <th>Observacion</th>
                                                <th>Devolver</th>
                                                <th>Utilizado</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @forelse ($transferencias as $index => $transferencia)
                                                <tr>
                                                    <td>{{ $index + 1 }}</td>
                                                    <td>{{ $transferencia['num_operacion'] }}</td>
                                                    <td>
                                                        {{ $transferencia['codigo'] }}
                                                        <input type="hidden" name="transferencias[{{ $index }}][id]" value="{{ $transferencia['id'] }}">
                                                    </td>
                                                    <td>{{ $transferencia['descripcion'] }}</td>
                                                    <td>{{ $transferencia['cantidad'] }}</td>
                                                    <td>
                                                        <input type="number" min="1" max="{{ $transferencia['cantidad'] }}" name="transferencias[{{ $index }}][cantidad]" class="form-control form-control-sm cantidad-input" value="{{ old("transferencias.$index.cantidad", $transferencia['cantidad']) }}">
                                                    </td>
                                                    <td>{{ $transferencia['tipo'] }}</td>
                                                    <td>{{ $transferencia['fecha_entrega'] }}</td>
                                                    <td>{{ $transferencia['emisor'] ?: '-' }}</td>
                                                    <td>{{ $transferencia['receptor'] ?: '-' }}</td>
                                                    <td>{{ $transferencia['ubicacion'] }}</td>
                                                    <td>{{ $transferencia['observacion'] ?: '-' }}</td>
                                                    <td class="checkbox-cell">
                                                        <input class="form-check-input transfer-devolver-input" type="checkbox" name="transferencias[{{ $index }}][devolver]" value="1" {{ old("transferencias.$index.devolver") ? 'checked' : '' }}>
                                                    </td>
                                                    <td class="checkbox-cell">
                                                        <input class="form-check-input transfer-utilizado-input" type="checkbox" name="transferencias[{{ $index }}][utilizado]" value="1" {{ old("transferencias.$index.utilizado") ? 'checked' : '' }} {{ $transferencia['puede_utilizarse'] ? '' : 'disabled' }}>
                                                    </td>
                                                </tr>
                                            @empty
                                                <tr>
                                                    <td colspan="14" class="items-empty-cell">
                                                        <div class="items-empty-state">
                                                            <strong>No hay transferencias activas para procesar</strong>
                                                            <span>Las transferencias pendientes apareceran aqui para devolverlas o marcarlas como utilizadas.</span>
                                                        </div>
                                                    </td>
                                                </tr>
                                            @endforelse
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </section>
                        @endif

                        <section class="section-card">
                            <div class="d-flex justify-content-end">
                                <button type="button" class="btn btn-brand action-btn" data-bs-toggle="modal" data-bs-target="#confirmarDevolucionModal">Procesar devolucion</button>
                            </div>
                        </section>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="confirmarDevolucionModal" tabindex="-1" aria-labelledby="confirmarDevolucionModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-sm modal-dialog-centered">
            <div class="modal-content border-0 shadow">
                <div class="modal-header">
                    <h2 class="modal-title fs-6" id="confirmarDevolucionModalLabel">Confirmar devolucion</h2>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <p class="mb-0 text-muted-brand">Esta accion actualizara inventario, estados y registros de devolucion. Desea continuar?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-primary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="button" id="confirmar-devolucion-btn" class="btn btn-brand">Confirmar</button>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        (() => {
            const form = document.getElementById('devolucion-form');
            const confirmarModalElement = document.getElementById('confirmarDevolucionModal');
            const confirmarModal = confirmarModalElement ? bootstrap.Modal.getOrCreateInstance(confirmarModalElement) : null;
            const confirmarBtn = document.getElementById('confirmar-devolucion-btn');

            if (!form) {
                return;
            }

            document.querySelectorAll('tr').forEach((row) => {
                const devolverInput = row.querySelector('.transfer-devolver-input');
                const utilizadoInput = row.querySelector('.transfer-utilizado-input');

                if (!(devolverInput instanceof HTMLInputElement) || !(utilizadoInput instanceof HTMLInputElement)) {
                    return;
                }

                devolverInput.addEventListener('change', () => {
                    if (devolverInput.checked) {
                        utilizadoInput.checked = false;
                    }
                });

                utilizadoInput.addEventListener('change', () => {
                    if (utilizadoInput.checked) {
                        devolverInput.checked = false;
                    }
                });
            });

            confirmarBtn?.addEventListener('click', () => {
                if (confirmarModal) {
                    confirmarModal.hide();
                }

                if (typeof form.requestSubmit === 'function') {
                    form.requestSubmit();
                    return;
                }

                form.submit();
            });
        })();
    </script>
@endpush
