@extends('layouts.dashboard.app')

@section('style')
<style>
    .doc-manager {
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 2px 15px rgba(0,0,0,0.08);
        overflow: hidden;
    }

    .doc-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 20px 25px;
        background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
        color: #fff;
    }

    .doc-header h4 {
        margin: 0;
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .doc-header .header-actions {
        display: flex;
        gap: 10px;
    }

    .doc-header .btn {
        padding: 8px 16px;
        font-size: 13px;
    }

    /* Toolbar */
    .doc-toolbar {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 15px 25px;
        background: #f8f9fa;
        border-bottom: 1px solid #eee;
        flex-wrap: wrap;
        gap: 15px;
    }

    .filter-chips {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
    }

    .filter-chip {
        padding: 6px 14px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 500;
        cursor: pointer;
        border: 1px solid #dee2e6;
        background: #fff;
        color: #495057;
        transition: all 0.2s;
        display: flex;
        align-items: center;
        gap: 5px;
    }

    .filter-chip:hover {
        border-color: #0d6efd;
        color: #0d6efd;
    }

    .filter-chip.active {
        background: #0d6efd;
        border-color: #0d6efd;
        color: #fff;
    }

    .filter-chip .count {
        background: rgba(0,0,0,0.1);
        padding: 2px 6px;
        border-radius: 10px;
        font-size: 10px;
    }

    .filter-chip.active .count {
        background: rgba(255,255,255,0.2);
    }

    /* Selection bar */
    .selection-bar {
        display: none;
        align-items: center;
        justify-content: space-between;
        padding: 12px 25px;
        background: #e7f1ff;
        border-bottom: 1px solid #b6d4fe;
    }

    .selection-bar.show {
        display: flex;
    }

    .selection-bar .selection-info {
        display: flex;
        align-items: center;
        gap: 15px;
    }

    .selection-bar .selection-count {
        font-weight: 600;
        color: #0d6efd;
    }

    .selection-bar .btn-group .btn {
        padding: 6px 12px;
        font-size: 12px;
    }

    /* Document Grid */
    .doc-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 20px;
        padding: 25px;
    }

    .doc-card {
        position: relative;
        border-radius: 10px;
        overflow: hidden;
        border: 2px solid transparent;
        background: #fff;
        box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        transition: all 0.3s;
        cursor: pointer;
    }

    .doc-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 5px 20px rgba(0,0,0,0.12);
    }

    .doc-card.selected {
        border-color: #0d6efd;
        box-shadow: 0 0 0 3px rgba(13, 110, 253, 0.2);
    }

    .doc-card .select-checkbox {
        position: absolute;
        top: 10px;
        left: 10px;
        width: 22px;
        height: 22px;
        border-radius: 50%;
        background: rgba(255,255,255,0.9);
        border: 2px solid #dee2e6;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 10;
        transition: all 0.2s;
        cursor: pointer;
    }

    .doc-card .select-checkbox i {
        display: none;
        color: #fff;
        font-size: 12px;
    }

    .doc-card.selected .select-checkbox {
        background: #0d6efd;
        border-color: #0d6efd;
    }

    .doc-card.selected .select-checkbox i {
        display: block;
    }

    .doc-card .doc-preview {
        height: 160px;
        background: #f8f9fa;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
    }

    .doc-card .doc-preview img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s;
    }

    .doc-card:hover .doc-preview img {
        transform: scale(1.05);
    }

    .doc-card .doc-preview .pdf-icon {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #dc3545;
    }

    .doc-card .doc-preview .pdf-icon i {
        font-size: 50px;
    }

    .doc-card .doc-preview .pdf-icon span {
        font-size: 12px;
        color: #6c757d;
        margin-top: 5px;
    }

    .doc-card .doc-info {
        padding: 12px;
        border-top: 1px solid #eee;
    }

    .doc-card .doc-type {
        display: inline-block;
        padding: 3px 8px;
        border-radius: 4px;
        font-size: 11px;
        font-weight: 500;
        background: #e9ecef;
        color: #495057;
    }

    .doc-card .doc-actions {
        position: absolute;
        top: 10px;
        right: 10px;
        display: flex;
        gap: 5px;
        opacity: 0;
        transition: opacity 0.2s;
    }

    .doc-card:hover .doc-actions {
        opacity: 1;
    }

    .doc-card .doc-actions .btn {
        width: 30px;
        height: 30px;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background: rgba(255,255,255,0.9);
        border: none;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }

    .doc-card .doc-actions .btn:hover {
        background: #fff;
    }

    /* Empty State */
    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #6c757d;
    }

    .empty-state i {
        font-size: 60px;
        color: #dee2e6;
        margin-bottom: 20px;
    }

    .empty-state h5 {
        color: #495057;
        margin-bottom: 10px;
    }

    /* Section divider */
    .section-divider {
        padding: 15px 25px;
        background: #f8f9fa;
        font-weight: 600;
        color: #495057;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .section-divider .badge {
        font-weight: normal;
    }

    /* Lightbox overlay */
    .lightbox-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0,0,0,0.9);
        z-index: 9999;
        align-items: center;
        justify-content: center;
    }

    .lightbox-overlay.show {
        display: flex;
    }

    .lightbox-overlay img {
        max-width: 90%;
        max-height: 90%;
        border-radius: 8px;
    }

    .lightbox-close {
        position: absolute;
        top: 20px;
        right: 20px;
        width: 40px;
        height: 40px;
        background: rgba(255,255,255,0.1);
        border: none;
        border-radius: 50%;
        color: #fff;
        font-size: 20px;
        cursor: pointer;
    }

    .lightbox-close:hover {
        background: rgba(255,255,255,0.2);
    }

    /* Responsive */
    @media (max-width: 768px) {
        .doc-header {
            flex-direction: column;
            gap: 15px;
            text-align: center;
        }

        .doc-toolbar {
            flex-direction: column;
            align-items: stretch;
        }

        .doc-grid {
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            padding: 15px;
        }

        .selection-bar {
            flex-direction: column;
            gap: 10px;
        }
    }
</style>
@endsection

@section('content')
<div class="container-fluid">
    <form action="{{ route('Document.pdf') }}" method="post" id="documentForm">
        @csrf
        <input type="hidden" name="attachements" id="selectedDocs" value="">

        <div class="doc-manager">
            <!-- Header -->
            <div class="doc-header">
                <h4>
                    <i class="uil uil-folder-open"></i>
                    Documents du Dossier
                </h4>
                <div class="header-actions">
                    <a href="{{ route('Dossier.show', $id) }}" class="btn btn-light">
                        <i class="uil uil-arrow-left me-1"></i> Retour
                    </a>
                    @if (Auth::user()->role_id == 4)
                        <a href="{{ route('Document.asigner', $id) }}" class="btn btn-success">
                            <i class="uil uil-file-check me-1"></i> Documents à Signer
                        </a>
                    @endif
                </div>
            </div>

            <!-- Toolbar with filters -->
            <div class="doc-toolbar">
                <div class="filter-chips">
                    <div class="filter-chip active" data-type="ALL" onclick="filterDocuments('ALL', this)">
                        <i class="uil uil-apps"></i> Tous
                        <span class="count">{{ count($imgs) + count($pdfs) }}</span>
                    </div>
                    @foreach ($types as $type)
                        @php
                            $typeCount = $imgs->where('type_document_id', $type->id)->count() + $pdfs->where('type_document_id', $type->id)->count();
                        @endphp
                        <div class="filter-chip" data-type="{{ $type->type }}" onclick="filterDocuments('{{ $type->type }}', this)">
                            {{ $type->type }}
                            <span class="count">{{ $typeCount }}</span>
                        </div>
                    @endforeach
                </div>

                <div>
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="selectAll()">
                        <i class="uil uil-check-square me-1"></i> Tout sélectionner
                    </button>
                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="deselectAll()">
                        <i class="uil uil-square me-1"></i> Désélectionner
                    </button>
                </div>
            </div>

            <!-- Selection Action Bar -->
            @can('download', App\Models\Document::class)
            <div class="selection-bar" id="selectionBar">
                <div class="selection-info">
                    <span class="selection-count"><span id="selectedCount">0</span> document(s) sélectionné(s)</span>
                    <button type="button" class="btn btn-link btn-sm text-danger" onclick="deselectAll()">
                        Annuler la sélection
                    </button>
                </div>
                <div class="btn-group">
                    <button type="submit" name="action" value="pdf" class="btn btn-success">
                        <i class="uil uil-file-download me-1"></i> PDF
                    </button>
                    <button type="submit" name="action" value="zip" class="btn btn-warning">
                        <i class="uil uil-file-download me-1"></i> ZIP
                    </button>
                    @if (Auth::user()->role_id == 4)
                        <button type="submit" name="action" value="delete" class="btn btn-danger" 
                            onclick="return confirm('Êtes-vous sûr de vouloir supprimer les documents sélectionnés?')">
                            <i class="uil uil-trash me-1"></i> Supprimer
                        </button>
                    @endif
                </div>
            </div>
            @endcan

            <!-- Images Section -->
            @if(count($imgs) > 0)
                <div class="section-divider">
                    <i class="uil uil-image"></i> Images
                    <span class="badge bg-primary">{{ count($imgs) }}</span>
                </div>
                <div class="doc-grid" id="imagesGrid">
                    @foreach ($imgs as $doc)
                        <div class="doc-card" 
                             data-id="{{ $doc->id }}" 
                             data-type="{{ $doc->typedocument->type ?? '' }}"
                             onclick="toggleSelect(this, {{ $doc->id }})">
                            
                            <div class="select-checkbox">
                                <i class="uil uil-check"></i>
                            </div>

                            <div class="doc-actions" onclick="event.stopPropagation()">
                                <button type="button" class="btn" title="Voir" 
                                    onclick="openLightbox('{{ Storage::disk('s3')->temporaryUrl($doc->path, now()->addMinutes(30)) }}')">
                                    <i class="uil uil-eye"></i>
                                </button>
                                <a href="{{ route('Document.edit', $doc->id) }}" class="btn" title="Modifier">
                                    <i class="uil uil-edit"></i>
                                </a>
                            </div>

                            <div class="doc-preview">
                                <img src="{{ Storage::disk('s3')->temporaryUrl($doc->path, now()->addMinutes(30)) }}" 
                                     alt="{{ $doc->typedocument->type ?? 'Document' }}"
                                     loading="lazy">
                            </div>

                            <div class="doc-info">
                                <span class="doc-type">{{ $doc->typedocument->type ?? 'Document' }}</span>
                            </div>
                        </div>
                    @endforeach
                </div>
            @endif

            <!-- PDFs Section -->
            @if(count($pdfs) > 0)
                <div class="section-divider">
                    <i class="uil uil-file-alt"></i> Documents PDF
                    <span class="badge bg-danger">{{ count($pdfs) }}</span>
                </div>
                <div class="doc-grid" id="pdfsGrid">
                    @foreach ($pdfs as $doc)
                        <div class="doc-card" 
                             data-id="{{ $doc->id }}" 
                             data-type="{{ $doc->typedocument->type ?? '' }}"
                             onclick="toggleSelect(this, {{ $doc->id }})">
                            
                            <div class="select-checkbox">
                                <i class="uil uil-check"></i>
                            </div>

                            <div class="doc-actions" onclick="event.stopPropagation()">
                                <a href="{{ Storage::disk('s3')->temporaryUrl($doc->path, now()->addMinutes(30)) }}" 
                                   target="_blank" class="btn" title="Ouvrir">
                                    <i class="uil uil-external-link-alt"></i>
                                </a>
                            </div>

                            <div class="doc-preview">
                                <div class="pdf-icon">
                                    <i class="uil uil-file-alt"></i>
                                    <span>PDF</span>
                                </div>
                            </div>

                            <div class="doc-info">
                                <span class="doc-type">{{ $doc->typedocument->type ?? 'PDF' }}</span>
                            </div>
                        </div>
                    @endforeach
                </div>
            @endif

            <!-- Empty State -->
            @if(count($imgs) == 0 && count($pdfs) == 0)
                <div class="empty-state">
                    <i class="uil uil-folder-open"></i>
                    <h5>Aucun document</h5>
                    <p>Ce dossier ne contient pas encore de documents.</p>
                    <a href="{{ route('Document.create', $id) }}" class="btn btn-primary mt-3">
                        <i class="uil uil-plus me-1"></i> Ajouter des documents
                    </a>
                </div>
            @endif
        </div>
    </form>
</div>

<!-- Lightbox -->
<div class="lightbox-overlay" id="lightbox" onclick="closeLightbox()">
    <button class="lightbox-close" onclick="closeLightbox()">
        <i class="uil uil-times"></i>
    </button>
    <img id="lightboxImage" src="" alt="Preview">
</div>
@endsection

@section('script')
<script>
let selectedDocuments = [];

// Toggle document selection
function toggleSelect(card, docId) {
    card.classList.toggle('selected');
    
    const index = selectedDocuments.indexOf(docId);
    if (index > -1) {
        selectedDocuments.splice(index, 1);
    } else {
        selectedDocuments.push(docId);
    }
    
    updateSelectionUI();
}

// Select all visible documents
function selectAll() {
    document.querySelectorAll('.doc-card:not([style*="display: none"])').forEach(card => {
        if (!card.classList.contains('selected')) {
            card.classList.add('selected');
            const docId = parseInt(card.dataset.id);
            if (!selectedDocuments.includes(docId)) {
                selectedDocuments.push(docId);
            }
        }
    });
    updateSelectionUI();
}

// Deselect all
function deselectAll() {
    document.querySelectorAll('.doc-card.selected').forEach(card => {
        card.classList.remove('selected');
    });
    selectedDocuments = [];
    updateSelectionUI();
}

// Update selection UI
function updateSelectionUI() {
    document.getElementById('selectedDocs').value = selectedDocuments.join(',');
    document.getElementById('selectedCount').textContent = selectedDocuments.length;
    
    const selectionBar = document.getElementById('selectionBar');
    if (selectedDocuments.length > 0) {
        selectionBar.classList.add('show');
    } else {
        selectionBar.classList.remove('show');
    }
}

// Filter documents by type
function filterDocuments(type, chip) {
    // Update active chip
    document.querySelectorAll('.filter-chip').forEach(c => c.classList.remove('active'));
    chip.classList.add('active');
    
    // Filter cards
    document.querySelectorAll('.doc-card').forEach(card => {
        if (type === 'ALL' || card.dataset.type === type) {
            card.style.display = 'block';
        } else {
            card.style.display = 'none';
        }
    });

    // Show/hide section dividers based on visible content
    updateSectionVisibility();
}

// Update section dividers visibility
function updateSectionVisibility() {
    const imagesGrid = document.getElementById('imagesGrid');
    const pdfsGrid = document.getElementById('pdfsGrid');
    
    if (imagesGrid) {
        const visibleImages = imagesGrid.querySelectorAll('.doc-card:not([style*="display: none"])').length;
        imagesGrid.previousElementSibling.style.display = visibleImages > 0 ? 'flex' : 'none';
        imagesGrid.style.display = visibleImages > 0 ? 'grid' : 'none';
    }
    
    if (pdfsGrid) {
        const visiblePdfs = pdfsGrid.querySelectorAll('.doc-card:not([style*="display: none"])').length;
        pdfsGrid.previousElementSibling.style.display = visiblePdfs > 0 ? 'flex' : 'none';
        pdfsGrid.style.display = visiblePdfs > 0 ? 'grid' : 'none';
    }
}

// Lightbox functions
function openLightbox(src) {
    event.stopPropagation();
    document.getElementById('lightboxImage').src = src;
    document.getElementById('lightbox').classList.add('show');
    document.body.style.overflow = 'hidden';
}

function closeLightbox() {
    document.getElementById('lightbox').classList.remove('show');
    document.body.style.overflow = '';
}

// Close lightbox on escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeLightbox();
    }
});
</script>
@endsection