// Upload functionality for Document Manager

document.addEventListener('DOMContentLoaded', function() {
    const uploadForm = document.getElementById('uploadForm');
    const documentFile = document.getElementById('documentFile');
    const documentName = document.getElementById('documentName');
    const controlNumber = document.getElementById('controlNumber');
    const documentCategory = document.getElementById('documentCategory');
    const documentType = document.getElementById('documentType');
    const documentDate = document.getElementById('documentDate');
    const documentDescription = document.getElementById('documentDescription');
    const documentTags = document.getElementById('documentTags');
    const uploadButton = document.getElementById('uploadButton');
    const uploadButtonText = document.getElementById('uploadButtonText');
    const uploadSpinner = document.getElementById('uploadSpinner');
    const uploadProgressCard = document.getElementById('uploadProgressCard');
    const uploadProgress = document.getElementById('uploadProgress');
    const uploadStatus = document.getElementById('uploadStatus');
    const successModal = new bootstrap.Modal(document.getElementById('successModal'));
    const mobileUploadModal = new bootstrap.Modal(document.getElementById('mobileUploadModal'));
    const mobileUploadBtn = document.getElementById('mobileUploadBtn');
    const qrCodeContainer = document.getElementById('qrCodeContainer');
    const dropZone = document.getElementById('drop-zone');
    const fileInfo = document.getElementById('file-info');
    let selectedFile = null;

    // Check license status to show premium features
    checkLicenseStatus();
    
    // Set default date to today
    if (documentDate) {
        const today = new Date().toISOString().split('T')[0];
        documentDate.value = today;
    }
    
    // Auto-fill document name from file name
    if (documentFile) {
        documentFile.addEventListener('change', function() {
            if (this.files && this.files.length > 0) {
                handleFiles(this.files);
            }
        });
    }
    
    // Handle file selection from drop zone click
    if (dropZone) {
        dropZone.addEventListener('click', () => documentFile.click());
    }

    // Handle drag and drop
    if (dropZone) {
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, preventDefaults, false);
            document.body.addEventListener(eventName, preventDefaults, false);
        });

        ['dragenter', 'dragover'].forEach(eventName => {
            dropZone.addEventListener(eventName, () => dropZone.classList.add('highlight'), false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, () => dropZone.classList.remove('highlight'), false);
        });

        dropZone.addEventListener('drop', handleDrop, false);
    }

    // Handle paste event on the whole page
    document.addEventListener('paste', handlePaste, false);

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        handleFiles(files);
    }

    function handlePaste(e) {
        const items = (e.clipboardData || e.originalEvent.clipboardData).items;
        let files = [];
        for (let i = 0; i < items.length; i++) {
            if (items[i].kind === 'file') {
                files.push(items[i].getAsFile());
            }
        }
        if (files.length > 0) {
            handleFiles(files);
        }
    }

    function handleFiles(files) {
        if (files.length > 0) {
            selectedFile = files[0];
            updateFileInfo(selectedFile);
            autofillFormFromFile(selectedFile);
        }
    }

    function updateFileInfo(file) {
        if (fileInfo) {
            if (file) {
                fileInfo.innerHTML = `<strong>Selected file:</strong> ${file.name} (${formatFileSize(file.size)})`;
            } else {
                fileInfo.innerHTML = '';
            }
        }
    }

    function autofillFormFromFile(file) {
        if (!file) return;

        const fileName = file.name.replace(/\.[^/.]+$/, ''); // Remove extension
        if (!documentName.value) {
            documentName.value = fileName;
        }

        const fileExt = file.name.split('.').pop().toLowerCase();
        if (documentType) {
            if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExt)) {
                documentType.value = 'image';
            } else if (fileExt === 'pdf') {
                documentType.value = 'pdf';
            } else if (['doc', 'docx'].includes(fileExt)) {
                documentType.value = 'word';
            } else {
                documentType.value = 'other';
            }
        }
    }

    // Handle form submission
    if (uploadForm) {
        uploadForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // Validate form
            const file = selectedFile;
            if (!file) {
                showAlert('Please select a file to upload.', 'danger');
                return;
            }
            
            // Check file size (max 10MB)
            const maxSize = 10 * 1024 * 1024; // 10MB
            
            if (file.size > maxSize) {
                showAlert('File is too large. Maximum file size is 10MB.', 'danger');
                return;
            }
            
            // Check file type
            const allowedTypes = ['application/pdf', 'image/jpeg', 'image/png', 'image/gif', 
                                 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
            
            if (!allowedTypes.includes(file.type) && !file.name.match(/\.(pdf|jpe?g|png|gif|docx?)$/i)) {
                showAlert('Invalid file type. Please upload a PDF, Word document, or image file.', 'danger');
                return;
            }
            
            // Prepare form data
            const formData = new FormData();
            formData.append('file', file);
            formData.append('name', documentName.value.trim());
            formData.append('control_number', 'DOC-' + (controlNumber.value.trim() || generateRandomId()));
            formData.append('category', documentCategory.value || 'Uncategorized');
            formData.append('document_type', documentType.value || 'other');
            formData.append('date', documentDate.value || new Date().toISOString().split('T')[0]);
            formData.append('description', documentDescription.value.trim());
            formData.append('tags', documentTags.value.trim());
            
            // Show upload progress
            uploadButton.disabled = true;
            uploadButtonText.textContent = 'Uploading...';
            uploadSpinner.classList.remove('d-none');
            uploadProgressCard.classList.remove('d-none');
            uploadProgress.style.width = '0%';
            uploadProgress.textContent = '0%';
            uploadStatus.textContent = 'Preparing upload...';
            
            try {
                // Create XMLHttpRequest for upload progress tracking
                const xhr = new XMLHttpRequest();
                
                // Upload progress event
                xhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        const percentComplete = Math.round((e.loaded / e.total) * 100);
                        uploadProgress.style.width = percentComplete + '%';
                        uploadProgress.textContent = percentComplete + '%';
                        uploadStatus.textContent = `Uploading: ${formatFileSize(e.loaded)} of ${formatFileSize(e.total)}`;
                    }
                });
                
                // Load event (upload complete)
                xhr.addEventListener('load', function() {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        const response = JSON.parse(xhr.responseText);
                        
                        if (response.success) {
                            // Show success message
                            uploadStatus.textContent = 'Upload complete! Processing document...';
                            uploadProgress.style.width = '100%';
                            uploadProgress.textContent = '100%';
                            
                            // Update UI for success
                            uploadStatus.textContent = 'Document processed successfully!';
                            uploadButtonText.textContent = 'Upload Complete';
                            
                            // Show success modal
                            document.getElementById('uploadedDocumentId').textContent = response.document_id || 'N/A';
                            successModal.show();
                            
                            // Reset form if user closes the modal without clicking the buttons
                            successModal._element.addEventListener('hidden.bs.modal', function() {
                                resetForm();
                            });
                            
                        } else {
                            throw new Error(response.error || 'Upload failed');
                        }
                    } else {
                        throw new Error('Upload failed with status ' + xhr.status);
                    }
                });
                
                // Error event
                xhr.addEventListener('error', function() {
                    throw new Error('Network error during upload');
                });
                
                // Open and send the request
                xhr.open('POST', '/api/upload', true);
                xhr.send(formData);
                
            } catch (error) {
                console.error('Upload error:', error);
                showAlert('Error uploading file: ' + (error.message || 'Unknown error'), 'danger');
                resetUploadUI();
            }
        });
    }
    
    // Handle success modal buttons
    document.querySelectorAll('[data-bs-dismiss="modal"]').forEach(button => {
        button.addEventListener('click', function() {
            resetForm();
        });
    });
    
    // Mobile upload button handler
    if (mobileUploadBtn) {
        mobileUploadBtn.addEventListener('click', async () => {
            try {
                const response = await fetch('/api/mobile/init');
                const data = await response.json();

                if (data.success) {
                    qrCodeContainer.innerHTML = `<img src="${data.qr_code}" alt="QR Code">`;
                    mobileUploadModal.show();
                    pollForUpload(data.session_id);
                } else {
                    showAlert('Could not initialize mobile upload.', 'danger');
                }
            } catch (error) {
                showAlert('Error setting up mobile upload.', 'danger');
            }
        });
    }

    let polling = false;
    async function pollForUpload(sessionId) {
        if (polling) return;
        polling = true;
        let intervalId = setInterval(async () => {
            if (!mobileUploadModal._isShown) {
                clearInterval(intervalId);
                polling = false;
                return;
            }

            try {
                const response = await fetch(`/api/mobile/status/${sessionId}`);
                const data = await response.json();

                if (data.success && data.status === 'completed') {
                    clearInterval(intervalId);
                    polling = false;
                    mobileUploadModal.hide();

                    const file = base64ToFile(data.file_content, data.filename);
                    handleFiles([file]);
                }
            } catch (error) {
                console.error('Polling error:', error);
            }
        }, 3000);
    }

    function base64ToFile(base64, filename) {
        const byteCharacters = atob(base64);
        const byteNumbers = new Array(byteCharacters.length);
        for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        const blob = new Blob([byteArray]);
        return new File([blob], filename);
    }

    // Load categories
    loadCategories();
});

// Check license status to show/hide premium features
async function checkLicenseStatus() {
    try {
        const response = await fetch('/api/license/status');
        if (response.ok) {
            const data = await response.json();
            if (data.success && data.web_features_enabled) {
                const mobileUploadBtn = document.getElementById('mobileUploadBtn');
                if (mobileUploadBtn) {
                    mobileUploadBtn.classList.remove('d-none');
                }
            }
        }
    } catch (error) {
        // This error is expected for non-premium users as the server won't be running.
        // We can safely ignore it and the button will remain hidden.
        console.log('License check failed, assuming non-premium.');
    }
}

// Load categories from the server
async function loadCategories() {
    try {
        const response = await fetch('/api/categories');
        const data = await response.json();
        
        if (data.success && data.data) {
            const categorySelect = document.getElementById('documentCategory');
            
            if (categorySelect) {
                // Save current value
                const currentValue = categorySelect.value;
                
                // Clear existing options except the first one
                while (categorySelect.options.length > 1) {
                    categorySelect.remove(1);
                }
                
                // Add new categories
                data.data.forEach(category => {
                    const option = document.createElement('option');
                    option.value = category.name;
                    option.textContent = category.name;
                    categorySelect.appendChild(option);
                });
                
                // Restore previous value if it still exists
                if (currentValue) {
                    const optionExists = Array.from(categorySelect.options).some(
                        opt => opt.value === currentValue
                    );
                    if (optionExists) {
                        categorySelect.value = currentValue;
                    }
                }
            }
        }
    } catch (error) {
        console.error('Error loading categories:', error);
    }
}

// Reset the upload form
function resetForm() {
    const form = document.getElementById('uploadForm');
    if (form) form.reset();
    
    selectedFile = null;
    updateFileInfo(null);
    
    // Reset UI state
    resetUploadUI();
    
    // Set default date to today
    const documentDate = document.getElementById('documentDate');
    if (documentDate) {
        const today = new Date().toISOString().split('T')[0];
        documentDate.value = today;
    }
    
    // Set focus to file input
    const documentFile = document.getElementById('documentFile');
    if (documentFile) documentFile.focus();
}

// Reset the upload UI elements
function resetUploadUI() {
    const uploadButton = document.getElementById('uploadButton');
    const uploadButtonText = document.getElementById('uploadButtonText');
    const uploadSpinner = document.getElementById('uploadSpinner');
    const uploadProgressCard = document.getElementById('uploadProgressCard');
    
    if (uploadButton) uploadButton.disabled = false;
    if (uploadButtonText) uploadButtonText.textContent = 'Upload Document';
    if (uploadSpinner) uploadSpinner.classList.add('d-none');
    if (uploadProgressCard) uploadProgressCard.classList.add('d-none');
}

// Show an alert message
function showAlert(message, type = 'info') {
    // Remove any existing alerts
    const existingAlerts = document.querySelectorAll('.alert');
    existingAlerts.forEach(alert => alert.remove());
    
    // Create alert element
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.role = 'alert';
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    
    // Add to the page
    const container = document.querySelector('.container');
    if (container) {
        container.insertBefore(alertDiv, container.firstChild);
        
        // Auto-dismiss after 5 seconds
        setTimeout(() => {
            const bsAlert = new bootstrap.Alert(alertDiv);
            bsAlert.close();
        }, 5000);
    }
}

// Generate a random ID for control number
function generateRandomId() {
    return Math.random().toString(36).substr(2, 8).toUpperCase();
}

// Format file size in human-readable format
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// Initialize tooltips
document.addEventListener('DOMContentLoaded', function() {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});
