/**
 * UI Feedback utilities for reports system
 * 
 * Provides loading indicators, success confirmations, and error messages
 * for report filtering and export operations.
 */

// Loading indicator management
const LoadingIndicator = {
    /**
     * Show loading indicator
     * @param {string} message - Loading message to display
     * @param {string} containerId - Optional container ID to show loading in
     */
    show: function(message = 'Loading...', containerId = null) {
        const loadingHtml = `
            <div class="loading-overlay" id="loadingOverlay">
                <div class="loading-spinner">
                    <div class="spinner-border text-primary" role="status">
                        <span class="sr-only">Loading...</span>
                    </div>
                    <p class="mt-3 text-white">${message}</p>
                </div>
            </div>
        `;
        
        if (containerId) {
            const container = document.getElementById(containerId);
            if (container) {
                container.insertAdjacentHTML('beforeend', loadingHtml);
            }
        } else {
            document.body.insertAdjacentHTML('beforeend', loadingHtml);
        }
    },
    
    /**
     * Hide loading indicator
     */
    hide: function() {
        const overlay = document.getElementById('loadingOverlay');
        if (overlay) {
            overlay.remove();
        }
    },
    
    /**
     * Update loading message
     * @param {string} message - New loading message
     */
    updateMessage: function(message) {
        const overlay = document.getElementById('loadingOverlay');
        if (overlay) {
            const messageElement = overlay.querySelector('p');
            if (messageElement) {
                messageElement.textContent = message;
            }
        }
    }
};

// Success message management
const SuccessMessage = {
    /**
     * Show success message
     * @param {string} message - Success message to display
     * @param {number} duration - Duration in milliseconds (default 3000)
     */
    show: function(message, duration = 3000) {
        const alertHtml = `
            <div class="alert alert-success alert-dismissible fade show position-fixed" 
                 role="alert" 
                 style="top: 20px; right: 20px; z-index: 9999; min-width: 300px;"
                 id="successAlert">
                <i class="fas fa-check-circle"></i>
                <strong>Success!</strong> ${message}
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', alertHtml);
        
        // Auto-dismiss after duration
        setTimeout(() => {
            const alert = document.getElementById('successAlert');
            if (alert) {
                alert.classList.remove('show');
                setTimeout(() => alert.remove(), 150);
            }
        }, duration);
    }
};

// Error message management
const ErrorMessage = {
    /**
     * Show error message
     * @param {string} message - Error message to display
     * @param {number} duration - Duration in milliseconds (default 5000)
     */
    show: function(message, duration = 5000) {
        const alertHtml = `
            <div class="alert alert-danger alert-dismissible fade show position-fixed" 
                 role="alert" 
                 style="top: 20px; right: 20px; z-index: 9999; min-width: 300px;"
                 id="errorAlert">
                <i class="fas fa-exclamation-triangle"></i>
                <strong>Error!</strong> ${message}
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', alertHtml);
        
        // Auto-dismiss after duration
        setTimeout(() => {
            const alert = document.getElementById('errorAlert');
            if (alert) {
                alert.classList.remove('show');
                setTimeout(() => alert.remove(), 150);
            }
        }, duration);
    }
};

// Filter application feedback
const FilterFeedback = {
    /**
     * Show filter application loading
     */
    showApplying: function() {
        LoadingIndicator.show('Applying filters...');
    },
    
    /**
     * Show filter applied success
     * @param {number} recordCount - Number of records returned
     */
    showApplied: function(recordCount) {
        LoadingIndicator.hide();
        SuccessMessage.show(`Filters applied successfully. ${recordCount} records found.`);
    },
    
    /**
     * Show filter error
     * @param {string} error - Error message
     */
    showError: function(error) {
        LoadingIndicator.hide();
        ErrorMessage.show(`Filter error: ${error}`);
    },
    
    /**
     * Show filter cleared
     */
    showCleared: function() {
        SuccessMessage.show('Filters cleared successfully.');
    }
};

// Export feedback
const ExportFeedback = {
    /**
     * Show export generation loading
     * @param {string} format - Export format (PDF or Excel)
     */
    showGenerating: function(format) {
        LoadingIndicator.show(`Generating ${format} export...`);
    },
    
    /**
     * Show export ready
     * @param {string} format - Export format
     */
    showReady: function(format) {
        LoadingIndicator.hide();
        SuccessMessage.show(`${format} export generated successfully. Download starting...`);
    },
    
    /**
     * Show export error
     * @param {string} error - Error message
     */
    showError: function(error) {
        LoadingIndicator.hide();
        ErrorMessage.show(`Export failed: ${error}`);
    }
};

// Form validation feedback
const ValidationFeedback = {
    /**
     * Show validation error on field
     * @param {string} fieldId - Field ID
     * @param {string} message - Error message
     */
    showFieldError: function(fieldId, message) {
        const field = document.getElementById(fieldId);
        if (field) {
            field.classList.add('is-invalid');
            
            // Remove existing feedback
            const existingFeedback = field.parentElement.querySelector('.invalid-feedback');
            if (existingFeedback) {
                existingFeedback.remove();
            }
            
            // Add new feedback
            const feedback = document.createElement('div');
            feedback.className = 'invalid-feedback';
            feedback.textContent = message;
            field.parentElement.appendChild(feedback);
        }
    },
    
    /**
     * Clear validation error on field
     * @param {string} fieldId - Field ID
     */
    clearFieldError: function(fieldId) {
        const field = document.getElementById(fieldId);
        if (field) {
            field.classList.remove('is-invalid');
            const feedback = field.parentElement.querySelector('.invalid-feedback');
            if (feedback) {
                feedback.remove();
            }
        }
    },
    
    /**
     * Clear all validation errors
     */
    clearAll: function() {
        document.querySelectorAll('.is-invalid').forEach(field => {
            field.classList.remove('is-invalid');
        });
        document.querySelectorAll('.invalid-feedback').forEach(feedback => {
            feedback.remove();
        });
    }
};

// Attach event listeners for filter forms
document.addEventListener('DOMContentLoaded', function() {
    // Handle filter form submissions
    const filterForms = document.querySelectorAll('form[data-filter-form]');
    filterForms.forEach(form => {
        form.addEventListener('submit', function(e) {
            // Validate form before submission
            const startDate = form.querySelector('[name="start_date"]');
            const endDate = form.querySelector('[name="end_date"]');
            
            if (startDate && endDate && startDate.value && endDate.value) {
                if (new Date(startDate.value) > new Date(endDate.value)) {
                    e.preventDefault();
                    ValidationFeedback.showFieldError('start_date', 'Start date must be before end date');
                    ErrorMessage.show('Invalid date range');
                    return false;
                }
            }
            
            // Show loading indicator
            FilterFeedback.showApplying();
        });
    });
    
    // Handle export button clicks
    const exportButtons = document.querySelectorAll('[data-export-btn]');
    exportButtons.forEach(button => {
        button.addEventListener('click', function() {
            const format = this.dataset.exportFormat || 'PDF';
            ExportFeedback.showGenerating(format);
            
            // Hide loading after a delay (actual download will trigger)
            setTimeout(() => {
                ExportFeedback.showReady(format);
            }, 2000);
        });
    });
    
    // Handle clear filters button
    const clearButtons = document.querySelectorAll('[data-clear-filters]');
    clearButtons.forEach(button => {
        button.addEventListener('click', function() {
            ValidationFeedback.clearAll();
            FilterFeedback.showCleared();
        });
    });
    
    // Clear field errors on input
    document.querySelectorAll('input, select').forEach(field => {
        field.addEventListener('input', function() {
            if (this.classList.contains('is-invalid')) {
                ValidationFeedback.clearFieldError(this.id);
            }
        });
    });
});

// CSS for loading overlay
const style = document.createElement('style');
style.textContent = `
    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.7);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 10000;
    }
    
    .loading-spinner {
        text-align: center;
    }
    
    .loading-spinner .spinner-border {
        width: 3rem;
        height: 3rem;
    }
    
    .loading-spinner p {
        font-size: 1.1rem;
        font-weight: 500;
    }
`;
document.head.appendChild(style);
