@extends('layouts.dashboard.app')

@section('style')
<style>
    .editor-page {
        background: #1a1a2e;
        min-height: 100vh;
        padding: 20px;
    }

    .editor-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 15px 20px;
        background: #16213e;
        border-radius: 10px;
        margin-bottom: 20px;
    }

    .editor-header .back-btn {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #fff;
        text-decoration: none;
        padding: 8px 16px;
        background: rgba(255,255,255,0.1);
        border-radius: 8px;
        transition: all 0.3s;
    }

    .editor-header .back-btn:hover {
        background: rgba(255,255,255,0.2);
        color: #fff;
    }

    .editor-header .doc-info {
        display: flex;
        align-items: center;
        gap: 15px;
    }

    .editor-header .doc-info .badge {
        padding: 8px 15px;
        font-size: 13px;
    }

    .editor-header .doc-title {
        color: #fff;
        font-size: 18px;
        font-weight: 600;
        margin: 0;
    }

    .editor-container {
        background: #0f0f23;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 10px 40px rgba(0,0,0,0.3);
    }

    /* Filerobot Editor Customization */
    .editor-wrapper {
        height: calc(100vh - 180px);
        min-height: 600px;
    }

    /* Loading State */
    .editor-loading {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 500px;
        color: #fff;
    }

    .editor-loading .spinner {
        width: 50px;
        height: 50px;
        border: 3px solid rgba(255,255,255,0.1);
        border-top-color: #0d6efd;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        to { transform: rotate(360deg); }
    }

    .editor-loading p {
        margin-top: 20px;
        color: #adb5bd;
    }

    /* Document Sidebar */
    .doc-sidebar {
        background: #16213e;
        border-radius: 10px;
        padding: 15px;
        height: calc(100vh - 180px);
        overflow-y: auto;
    }

    .doc-sidebar h6 {
        color: #fff;
        font-size: 14px;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid rgba(255,255,255,0.1);
    }

    .doc-thumbnail {
        width: 100%;
        aspect-ratio: 4/3;
        object-fit: cover;
        border-radius: 8px;
        cursor: pointer;
        border: 2px solid transparent;
        transition: all 0.3s;
        margin-bottom: 10px;
    }

    .doc-thumbnail:hover {
        border-color: #0d6efd;
        transform: scale(1.02);
    }

    .doc-thumbnail.active {
        border-color: #10b981;
        box-shadow: 0 0 15px rgba(16, 185, 129, 0.3);
    }

    .doc-type-badge {
        display: block;
        text-align: center;
        padding: 5px 10px;
        background: rgba(255,255,255,0.1);
        border-radius: 5px;
        color: #adb5bd;
        font-size: 11px;
        margin-bottom: 15px;
    }

    /* Save Success Modal */
    .save-success {
        position: fixed;
        top: 20px;
        right: 20px;
        background: #10b981;
        color: #fff;
        padding: 15px 25px;
        border-radius: 10px;
        display: none;
        align-items: center;
        gap: 10px;
        z-index: 9999;
        animation: slideIn 0.3s ease;
    }

    .save-success.show {
        display: flex;
    }

    @keyframes slideIn {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }

    /* Filter buttons */
    .filter-tabs {
        display: flex;
        gap: 8px;
        margin-bottom: 15px;
        flex-wrap: wrap;
    }

    .filter-tabs .btn {
        padding: 5px 12px;
        font-size: 11px;
        border-radius: 20px;
    }

    .filter-tabs .btn.active {
        background: #0d6efd;
        color: #fff;
    }
</style>
@endsection

@section('content')
<div class="editor-page">
    <!-- Header -->
    <div class="editor-header">
        <a href="{{ route('Dossier.show', $dossier->id) }}" class="back-btn">
            <i class="uil uil-arrow-left"></i>
            <span>Retour au Dossier</span>
        </a>
        
        <div class="doc-info">
            <h5 class="doc-title">
                <i class="uil uil-edit me-2"></i> Éditer Document
            </h5>
            <span class="badge bg-info">{{ $dossier->ref }}</span>
            <span class="badge bg-secondary">{{ $document->typedocument->type ?? 'Document' }}</span>
        </div>

        <div class="header-actions">
            <form action="{{ route('Document.update', $document->id) }}" method="POST" id="saveForm">
                @csrf
                @method('PUT')
                <input type="hidden" name="img" id="editedImageData" value="">
                <button type="submit" class="btn btn-success" id="saveBtn" disabled>
                    <i class="uil uil-save me-1"></i> Enregistrer
                </button>
            </form>
        </div>
    </div>

    <div class="row">
        <!-- Documents Sidebar -->
        <div class="col-md-2">
            <div class="doc-sidebar">
                <h6><i class="uil uil-images me-2"></i> Documents</h6>
                
                <!-- Filter Tabs -->
                <div class="filter-tabs">
                    <button class="btn btn-outline-light btn-sm active" onclick="filterDocs('ALL')">Tous</button>
                    @foreach($typedocuments as $type)
                        <button class="btn btn-outline-light btn-sm" onclick="filterDocs('{{ $type->type }}')">
                            {{ $type->type }}
                        </button>
                    @endforeach
                </div>

                <!-- Document Thumbnails -->
                <div id="docList">
                    @foreach($documents as $doc)
                        @php
                            $thumbUrl = Storage::disk('s3')->temporaryUrl($doc->path, now()->addMinutes(30));
                        @endphp
                        <div class="doc-item" data-type="{{ $doc->typedocument->type ?? '' }}">
                            <img src="{{ $thumbUrl }}" 
                                 alt="{{ $doc->typedocument->type ?? 'Document' }}"
                                 class="doc-thumbnail {{ $doc->id == $document->id ? 'active' : '' }}"
                                 onclick="loadDocument('{{ $thumbUrl }}', {{ $doc->id }})"
                                 data-id="{{ $doc->id }}">
                            <span class="doc-type-badge">{{ $doc->typedocument->type ?? 'Doc' }}</span>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>

        <!-- Editor Container -->
        <div class="col-md-10">
            <div class="editor-container">
                <!-- Loading State -->
                <div class="editor-loading" id="editorLoading">
                    <div class="spinner"></div>
                    <p>Chargement de l'éditeur...</p>
                </div>

                <!-- Editor Wrapper -->
                <div class="editor-wrapper" id="editorWrapper" style="display: none;"></div>
            </div>
        </div>
    </div>
</div>

<!-- Save Success Notification -->
<div class="save-success" id="saveSuccess">
    <i class="uil uil-check-circle"></i>
    <span>Document enregistré avec succès!</span>
</div>

<!-- Hidden input for current document URL -->
<input type="hidden" id="currentDocUrl" value="{{ Storage::disk('s3')->temporaryUrl($document->path, now()->addMinutes(30)) }}">
<input type="hidden" id="currentDocId" value="{{ $document->id }}">
@endsection

@section('script')
<script src="https://scaleflex.cloudimg.io/v7/plugins/filerobot-image-editor/latest/filerobot-image-editor.min.js"></script>

<script>
let filerobotImageEditor = null;
let hasChanges = false;

document.addEventListener('DOMContentLoaded', function() {
    initEditor(document.getElementById('currentDocUrl').value);
});

function initEditor(imageUrl) {
    const { TABS, TOOLS } = FilerobotImageEditor;
    
    // Hide loading, show editor
    document.getElementById('editorLoading').style.display = 'none';
    document.getElementById('editorWrapper').style.display = 'block';
    
    // Destroy previous instance if exists
    if (filerobotImageEditor) {
        filerobotImageEditor.terminate();
    }

    const config = {
        source: imageUrl,
        
        // Save callback
        onSave: (editedImageObject, designState) => {
            console.log('Image saved:', editedImageObject);
            
            // Set the base64 data to hidden input
            document.getElementById('editedImageData').value = editedImageObject.imageBase64;
            document.getElementById('saveBtn').disabled = false;
            hasChanges = true;
            
            // Show success notification
            showNotification('Image modifiée! Cliquez sur Enregistrer pour sauvegarder.');
        },
        
        onModify: (currentImageDesignState) => {
            hasChanges = true;
            document.getElementById('saveBtn').disabled = false;
        },

        // Common annotations settings
        annotationsCommon: {
            fill: '#ff0000',
            stroke: '#ff0000',
            strokeWidth: 2,
        },

        // Text tool defaults
        Text: {
            text: '{{ $dossier->ref }}',
            fonts: [
                'Arial',
                'Helvetica',
                'Times New Roman',
                'Courier New',
                'Georgia',
                'Verdana'
            ],
        },

        // Rotate settings
        Rotate: {
            angle: 90,
            componentType: 'buttons'
        },

        // Crop presets
        Crop: {
            presetsItems: [
                {
                    titleKey: 'A4 Portrait',
                    descriptionKey: '210x297mm',
                    ratio: 210 / 297,
                },
                {
                    titleKey: 'A4 Paysage',
                    descriptionKey: '297x210mm',
                    ratio: 297 / 210,
                },
                {
                    titleKey: 'Carré',
                    descriptionKey: '1:1',
                    ratio: 1,
                },
                {
                    titleKey: '4:3',
                    descriptionKey: 'Standard',
                    ratio: 4 / 3,
                },
                {
                    titleKey: '16:9',
                    descriptionKey: 'Widescreen',
                    ratio: 16 / 9,
                },
            ],
        },

        // Available tabs
        tabsIds: [
            TABS.ADJUST,
            TABS.FINETUNE,
            TABS.FILTERS,
            TABS.ANNOTATE,
            TABS.RESIZE,
        ],
        
        // Default tab and tool
        defaultTabId: TABS.ANNOTATE,
        defaultToolId: TOOLS.TEXT,

        // French translations
        translations: {
            save: 'Appliquer',
            saveAs: 'Enregistrer sous',
            back: 'Retour',
            loading: 'Chargement...',
            resetOperations: 'Réinitialiser',
            changesLoseConfirmation: 'Vos modifications seront perdues. Continuer?',
            changesLoseConfirmationHint: 'Les modifications non enregistrées seront perdues.',
            cancel: 'Annuler',
            continue: 'Continuer',
            undoTitle: 'Annuler',
            redoTitle: 'Rétablir',
            showImageTitle: 'Afficher l\'image',
            zoomInTitle: 'Zoom avant',
            zoomOutTitle: 'Zoom arrière',
            toggleZoomMenuTitle: 'Menu zoom',
            adjustTab: 'Ajuster',
            finetuneTab: 'Réglages',
            filtersTab: 'Filtres',
            watermarkTab: 'Filigrane',
            annotateTab: 'Annoter',
            resizeTab: 'Redimensionner',
            brightness: 'Luminosité',
            contrast: 'Contraste',
            hue: 'Teinte',
            saturation: 'Saturation',
            blur: 'Flou',
            warmth: 'Chaleur',
            rotate: 'Rotation',
            crop: 'Recadrer',
            flipX: 'Retourner H',
            flipY: 'Retourner V',
            text: 'Texte',
            line: 'Ligne',
            rect: 'Rectangle',
            ellipse: 'Ellipse',
            polygon: 'Polygone',
            arrow: 'Flèche',
            pen: 'Crayon',
            image: 'Image',
        },

        // Theme customization
        theme: {
            palette: {
                'bg-primary': '#1a1a2e',
                'bg-primary-active': '#16213e',
                'bg-secondary': '#0f0f23',
                'accent-primary': '#0d6efd',
                'accent-primary-active': '#0b5ed7',
                'icons-primary': '#ffffff',
                'icons-secondary': '#adb5bd',
                'borders-primary': '#2d2d44',
                'borders-secondary': '#3d3d5c',
                'txt-primary': '#ffffff',
                'txt-secondary': '#adb5bd',
                'txt-placeholder': '#6c757d',
                'warning': '#ffc107',
                'error': '#dc3545',
                'success': '#10b981',
            },
            typography: {
                fontFamily: 'system-ui, -apple-system, sans-serif',
            },
        },

        // Save options
        savingPixelRatio: 2,
        previewPixelRatio: window.devicePixelRatio || 1,
    };

    // Initialize editor
    filerobotImageEditor = new FilerobotImageEditor(
        document.getElementById('editorWrapper'),
        config
    );

    filerobotImageEditor.render({
        onClose: (closingReason) => {
            console.log('Editor closing:', closingReason);
            if (hasChanges && closingReason === 'close-button-clicked') {
                if (!confirm('Vous avez des modifications non enregistrées. Quitter quand même?')) {
                    return false;
                }
            }
        },
    });
}

// Load different document
function loadDocument(url, docId) {
    if (hasChanges) {
        if (!confirm('Vous avez des modifications non enregistrées. Changer de document?')) {
            return;
        }
    }

    // Update active state
    document.querySelectorAll('.doc-thumbnail').forEach(el => el.classList.remove('active'));
    document.querySelector(`.doc-thumbnail[data-id="${docId}"]`).classList.add('active');
    
    // Update hidden inputs
    document.getElementById('currentDocId').value = docId;
    
    // Update form action
    document.getElementById('saveForm').action = `/Document/${docId}`;
    
    // Reload editor with new image
    hasChanges = false;
    document.getElementById('saveBtn').disabled = true;
    document.getElementById('editorLoading').style.display = 'flex';
    document.getElementById('editorWrapper').style.display = 'none';
    
    setTimeout(() => {
        initEditor(url);
    }, 300);
}

// Filter documents
function filterDocs(type) {
    // Update button states
    document.querySelectorAll('.filter-tabs .btn').forEach(btn => {
        btn.classList.remove('active');
        if (btn.textContent.trim() === type || (type === 'ALL' && btn.textContent.trim() === 'Tous')) {
            btn.classList.add('active');
        }
    });

    // Filter items
    document.querySelectorAll('.doc-item').forEach(item => {
        if (type === 'ALL' || item.dataset.type === type) {
            item.style.display = 'block';
        } else {
            item.style.display = 'none';
        }
    });
}

// Show notification
function showNotification(message) {
    const notification = document.getElementById('saveSuccess');
    notification.querySelector('span').textContent = message;
    notification.classList.add('show');
    
    setTimeout(() => {
        notification.classList.remove('show');
    }, 3000);
}

// Warn before leaving with unsaved changes
window.addEventListener('beforeunload', (e) => {
    if (hasChanges) {
        e.preventDefault();
        e.returnValue = '';
    }
});
</script>
@endsection