/**
 * AIReportInterface - UI component pour accéder aux rapports IA
 * Provides buttons and interface for accessing AI reports and explanations
 */

import componentRegistry from './ComponentRegistry.js';

class AIReportInterface {
    constructor(llmValidator, config = {}) {
        this.llmValidator = llmValidator;
        this.config = {
            showInline: config.showInline !== false, // Show reports inline by default
            showDownloadButtons: config.showDownloadButtons !== false,
            position: config.position || 'bottom-right', // Position in UI
            autoShow: config.autoShow !== false, // Auto-show after exercises
            ...config
        };

        this.container = null;
        this.isVisible = false;

        console.log('📊 AIReportInterface initialized');
    }

    /**
     * Create and insert the report interface into the DOM
     * @param {HTMLElement} parentContainer - Parent element
     */
    create(parentContainer) {
        if (this.container) {
            console.warn('⚠️ AIReportInterface already created');
            return;
        }

        this.container = document.createElement('div');
        this.container.className = `ai-report-interface position-${this.config.position}`;
        this.container.innerHTML = this._generateHTML();

        // Style the component
        this._applyStyles();

        // Add event listeners
        this._attachEventListeners();

        // Insert into parent
        parentContainer.appendChild(this.container);

        console.log('📊 AIReportInterface created and inserted into DOM');
    }

    /**
     * Generate the HTML structure
     * @private
     */
    _generateHTML() {
        return `
            <div class="ai-report-panel" ${!this.config.showInline ? 'style="display: none;"' : ''}>
                <div class="ai-report-header">
                    <h4>📚 Rapport IA</h4>
                    <button class="ai-report-toggle" title="Masquer/Afficher">−</button>
                </div>

                <div class="ai-report-content">
                    <div class="ai-report-summary">
                        <p class="ai-report-status">Aucune session active</p>
                    </div>

                    ${this.config.showDownloadButtons ? `
                        <div class="ai-report-actions">
                            <button class="btn-small btn-outline" id="viewReportBtn">
                                👁️ Voir le rapport
                            </button>

                            <div class="ai-report-download-group">
                                <button class="btn-small btn-primary" id="downloadTextBtn">
                                    📄 Texte
                                </button>
                                <button class="btn-small btn-primary" id="downloadHtmlBtn">
                                    🌐 HTML
                                </button>
                                <button class="btn-small btn-primary" id="downloadJsonBtn">
                                    📋 JSON
                                </button>
                            </div>
                        </div>
                    ` : ''}

                    <div class="ai-report-inline-view" id="inlineReportView" style="display: none;">
                        <div class="ai-report-inline-content"></div>
                        <button class="btn-small btn-outline" id="closeInlineBtn">Fermer</button>
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * Apply CSS styles to the component
     * @private
     */
    _applyStyles() {
        const style = document.createElement('style');
        style.textContent = `
            .ai-report-interface {
                position: fixed;
                z-index: 1000;
                max-width: 350px;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            }

            .ai-report-interface.position-bottom-right {
                bottom: 20px;
                right: 20px;
            }

            .ai-report-interface.position-bottom-left {
                bottom: 20px;
                left: 20px;
            }

            .ai-report-interface.position-top-right {
                top: 20px;
                right: 20px;
            }

            .ai-report-panel {
                background: white;
                border: 1px solid #e5e7eb;
                border-radius: 12px;
                box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
                overflow: hidden;
                transition: all 0.3s ease;
            }

            .ai-report-header {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 12px 16px;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }

            .ai-report-header h4 {
                margin: 0;
                font-size: 14px;
                font-weight: 600;
            }

            .ai-report-toggle {
                background: none;
                border: none;
                color: white;
                font-size: 18px;
                cursor: pointer;
                padding: 0;
                width: 24px;
                height: 24px;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 4px;
                transition: background-color 0.2s ease;
            }

            .ai-report-toggle:hover {
                background-color: rgba(255, 255, 255, 0.2);
            }

            .ai-report-content {
                padding: 16px;
            }

            .ai-report-summary {
                margin-bottom: 16px;
            }

            .ai-report-status {
                margin: 0;
                font-size: 13px;
                color: #6b7280;
                text-align: center;
                padding: 8px;
                background: #f9fafb;
                border-radius: 6px;
            }

            .ai-report-actions {
                display: flex;
                flex-direction: column;
                gap: 12px;
            }

            .ai-report-download-group {
                display: flex;
                gap: 6px;
                justify-content: space-between;
            }

            .btn-small {
                padding: 6px 12px;
                font-size: 12px;
                border-radius: 6px;
                border: 1px solid #e5e7eb;
                cursor: pointer;
                font-weight: 500;
                transition: all 0.2s ease;
                text-align: center;
                flex: 1;
            }

            .btn-small.btn-primary {
                background: #3b82f6;
                color: white;
                border-color: #3b82f6;
            }

            .btn-small.btn-primary:hover {
                background: #2563eb;
                border-color: #2563eb;
            }

            .btn-small.btn-outline {
                background: white;
                color: #374151;
                border-color: #d1d5db;
            }

            .btn-small.btn-outline:hover {
                background: #f9fafb;
                border-color: #9ca3af;
            }

            .ai-report-inline-view {
                margin-top: 16px;
                padding: 12px;
                background: #f8fafc;
                border-radius: 8px;
                border: 1px solid #e2e8f0;
            }

            .ai-report-inline-content {
                max-height: 300px;
                overflow-y: auto;
                font-size: 12px;
                line-height: 1.5;
                white-space: pre-wrap;
                font-family: 'Monaco', 'Consolas', monospace;
                margin-bottom: 12px;
            }

            .ai-report-panel.collapsed .ai-report-content {
                display: none;
            }

            .ai-report-panel.collapsed .ai-report-toggle::after {
                content: '+';
            }

            @media (max-width: 768px) {
                .ai-report-interface {
                    position: fixed;
                    bottom: 10px;
                    left: 10px;
                    right: 10px;
                    max-width: none;
                }

                .ai-report-download-group {
                    flex-direction: column;
                    gap: 8px;
                }
            }
        `;

        document.head.appendChild(style);
    }

    /**
     * Attach event listeners
     * @private
     */
    _attachEventListeners() {
        if (!this.container) return;

        // Toggle panel
        const toggleBtn = this.container.querySelector('.ai-report-toggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => this.toggle());
        }

        // View report inline
        const viewReportBtn = this.container.querySelector('#viewReportBtn');
        if (viewReportBtn) {
            viewReportBtn.addEventListener('click', () => this.showInlineReport());
        }

        // Download buttons
        const downloadTextBtn = this.container.querySelector('#downloadTextBtn');
        if (downloadTextBtn) {
            downloadTextBtn.addEventListener('click', () => this.downloadReport('text'));
        }

        const downloadHtmlBtn = this.container.querySelector('#downloadHtmlBtn');
        if (downloadHtmlBtn) {
            downloadHtmlBtn.addEventListener('click', () => this.downloadReport('html'));
        }

        const downloadJsonBtn = this.container.querySelector('#downloadJsonBtn');
        if (downloadJsonBtn) {
            downloadJsonBtn.addEventListener('click', () => this.downloadReport('json'));
        }

        // Close inline view
        const closeInlineBtn = this.container.querySelector('#closeInlineBtn');
        if (closeInlineBtn) {
            closeInlineBtn.addEventListener('click', () => this.hideInlineReport());
        }
    }

    /**
     * Update the status display
     * @param {string} message - Status message
     * @param {string} type - Status type ('info', 'success', 'warning')
     */
    updateStatus(message, type = 'info') {
        if (!this.container) return;

        const statusElement = this.container.querySelector('.ai-report-status');
        if (statusElement) {
            statusElement.textContent = message;
            statusElement.className = `ai-report-status ai-report-status-${type}`;
        }
    }

    /**
     * Notify about session start
     * @param {Object} sessionInfo - Session information
     */
    onSessionStart(sessionInfo) {
        this.updateStatus(`📚 Session active: ${sessionInfo.bookId}/${sessionInfo.chapterId}`, 'success');

        if (this.config.autoShow) {
            this.show();
        }
    }

    /**
     * Notify about session end
     * @param {Object} sessionStats - Session statistics
     */
    onSessionEnd(sessionStats) {
        const exerciseCount = sessionStats.exerciseCount || 0;
        const avgScore = sessionStats.averageScore || 0;

        this.updateStatus(
            `✅ Session terminée: ${exerciseCount} exercices, ${Math.round(avgScore)}% moyen`,
            'success'
        );
    }

    /**
     * Show inline report
     */
    async showInlineReport() {
        if (!this.llmValidator || !this.llmValidator.config.enableReporting) {
            alert('Le système de rapport n\'est pas disponible');
            return;
        }

        try {
            const report = this.llmValidator.getReport('text');
            const inlineView = this.container.querySelector('#inlineReportView');
            const inlineContent = this.container.querySelector('.ai-report-inline-content');

            if (inlineContent && inlineView) {
                inlineContent.textContent = report;
                inlineView.style.display = 'block';
            }
        } catch (error) {
            alert(`Erreur lors de la génération du rapport: ${error.message}`);
        }
    }

    /**
     * Hide inline report
     */
    hideInlineReport() {
        const inlineView = this.container.querySelector('#inlineReportView');
        if (inlineView) {
            inlineView.style.display = 'none';
        }
    }

    /**
     * Download report in specified format
     * @param {string} format - Report format ('text', 'html', 'json')
     */
    async downloadReport(format) {
        if (!this.llmValidator || !this.llmValidator.config.enableReporting) {
            alert('Le système de rapport n\'est pas disponible');
            return;
        }

        try {
            await this.llmValidator.exportReport(format);
            this.updateStatus(`📥 Rapport ${format.toUpperCase()} téléchargé`, 'success');

            // Reset status after 3 seconds
            setTimeout(() => {
                this.updateStatus('Rapport disponible au téléchargement', 'info');
            }, 3000);
        } catch (error) {
            alert(`Erreur lors du téléchargement: ${error.message}`);
        }
    }

    /**
     * Show the report interface
     */
    show() {
        if (!this.container) return;
        this.container.style.display = 'block';
        this.isVisible = true;
    }

    /**
     * Hide the report interface
     */
    hide() {
        if (!this.container) return;
        this.container.style.display = 'none';
        this.isVisible = false;
    }

    /**
     * Toggle the report interface visibility
     */
    toggle() {
        const panel = this.container.querySelector('.ai-report-panel');
        if (panel) {
            panel.classList.toggle('collapsed');
        }
    }

    /**
     * Destroy the component and clean up
     */
    destroy() {
        if (this.container && this.container.parentNode) {
            this.container.parentNode.removeChild(this.container);
        }
        this.container = null;
        console.log('📊 AIReportInterface destroyed');
    }
}

// Register the component
componentRegistry.register('aiReportInterface', AIReportInterface);

export default AIReportInterface;