/**
 * UnifiedDRS - Modern DRS implementation using extracted UI components
 * Replaces individual DRS modules with a unified, component-based approach
 */

import Module from '../core/Module.js';
import componentRegistry from '../components/ComponentRegistry.js';

class UnifiedDRS extends Module {
    constructor(name, dependencies, config) {
        super(name, ['eventBus', 'contentLoader']);

        // Validate dependencies
        if (!dependencies.eventBus) {
            throw new Error('UnifiedDRS requires EventBus dependency');
        }
        if (!dependencies.contentLoader) {
            throw new Error('UnifiedDRS requires ContentLoader dependency');
        }

        this._eventBus = dependencies.eventBus;
        this._contentLoader = dependencies.contentLoader;
        this._config = {
            exerciseTypes: ['text', 'audio', 'image', 'grammar'],
            defaultDifficulty: 'medium',
            showProgress: true,
            showHints: true,
            autoNext: false,
            ...config
        };

        // UI state
        this._currentExercise = null;
        this._currentStep = 0;
        this._totalSteps = 0;
        this._userProgress = {
            correct: 0,
            total: 0,
            hints: 0,
            timeSpent: 0
        };

        // Component instances
        this._components = {
            mainCard: null,
            progressBar: null,
            nextButton: null,
            hintButton: null,
            hintPanel: null,
            resultPanel: null
        };

        // Container and timing
        this._container = null;
        this._isActive = false;
        this._startTime = null;

        Object.seal(this);
    }

    async init() {
        this._validateNotDestroyed();

        console.log('🎓 Initializing Unified DRS...');

        // Initialize component registry
        await componentRegistry.init();

        // Set up event listeners
        this._eventBus.on('drs:start', this._handleStart.bind(this), this.name);
        this._eventBus.on('drs:next', this._handleNext.bind(this), this.name);
        this._eventBus.on('drs:hint', this._handleHint.bind(this), this.name);
        this._eventBus.on('drs:submit', this._handleSubmit.bind(this), this.name);
        this._eventBus.on('content:loaded', this._handleContentLoaded.bind(this), this.name);

        this._setInitialized();
        console.log('✅ Unified DRS initialized');
    }

    async destroy() {
        this._validateNotDestroyed();

        console.log('🧹 Destroying Unified DRS...');

        // Clean up UI
        this._cleanupUI();

        // Clean up components
        Object.values(this._components).forEach(component => {
            if (component && componentRegistry) {
                componentRegistry.destroy(component);
            }
        });

        this._setDestroyed();
        console.log('✅ Unified DRS destroyed');
    }

    // Public API

    /**
     * Start a new exercise session
     * @param {HTMLElement} container - Container element
     * @param {Object} exerciseConfig - Exercise configuration
     */
    async start(container, exerciseConfig = {}) {
        this._validateInitialized();

        if (!container) {
            throw new Error('Container element is required');
        }

        console.log('🎯 Starting Unified DRS exercise...');

        this._container = container;
        this._currentStep = 0;
        this._totalSteps = 0;
        this._userProgress = { correct: 0, total: 0, hints: 0, timeSpent: 0 };
        this._isActive = true;

        // Load exercise content
        const exerciseType = exerciseConfig.type || this._config.exerciseTypes[0];
        const content = await this._loadExerciseContent(exerciseType, exerciseConfig);

        if (!content) {
            throw new Error(`Failed to load exercise content for type: ${exerciseType}`);
        }

        this._currentExercise = content;
        this._totalSteps = content.steps ? content.steps.length : 1;

        // Create UI
        await this._createUI();

        // Start first step
        this._showCurrentStep();

        // Start timing
        this._startTime = Date.now();

        // Emit started event
        this._eventBus.emit('drs:started', {
            type: exerciseType,
            steps: this._totalSteps,
            config: exerciseConfig
        }, this.name);

        console.log(`✅ Exercise started: ${exerciseType} (${this._totalSteps} steps)`);
    }

    /**
     * Get current progress
     */
    getProgress() {
        return {
            currentStep: this._currentStep + 1,
            totalSteps: this._totalSteps,
            percentage: this._totalSteps > 0 ? Math.round(((this._currentStep + 1) / this._totalSteps) * 100) : 0,
            userStats: { ...this._userProgress },
            timeSpent: this._startTime ? Date.now() - this._startTime : 0
        };
    }

    /**
     * Check if exercise is currently active
     */
    isActive() {
        return this._isActive;
    }

    // Private methods

    /**
     * Load exercise content based on type
     */
    async _loadExerciseContent(type, config) {
        try {
            console.log(`📚 Loading ${type} exercise content...`);

            // Request content from ContentLoader
            const contentRequest = {
                type: 'exercise',
                subtype: type,
                difficulty: config.difficulty || this._config.defaultDifficulty,
                bookId: config.bookId,
                chapterId: config.chapterId,
                ...config
            };

            console.log('📋 UnifiedDRS content request:', contentRequest);
            const content = await this._contentLoader.loadExercise(contentRequest);

            console.log(`✅ UnifiedDRS content loaded:`, {
                title: content.title,
                stepsCount: content.steps ? content.steps.length : 0,
                hasSteps: !!content.steps,
                contentKeys: Object.keys(content),
                firstStep: content.steps ? content.steps[0] : null
            });

            return content;
        } catch (error) {
            console.error(`❌ Failed to load ${type} exercise:`, error);
            return null;
        }
    }

    /**
     * Create the main UI using components
     */
    async _createUI() {
        if (!this._container) return;

        // Clear container
        this._container.innerHTML = '';

        // Create main exercise card
        this._components.mainCard = componentRegistry.create('Card', {
            title: this._currentExercise.title || 'Exercise',
            type: 'exercise',
            className: 'drs-main-card'
        });

        // Create progress bar if enabled
        if (this._config.showProgress) {
            this._components.progressBar = componentRegistry.create('ProgressBar', {
                value: 0,
                max: this._totalSteps,
                color: 'primary',
                showLabel: true,
                className: 'drs-progress'
            });
        }

        // Create navigation buttons
        this._components.nextButton = componentRegistry.create('Button', {
            text: this._currentStep === this._totalSteps - 1 ? 'Finish' : 'Next',
            type: 'primary',
            onClick: () => this._handleNext(),
            className: 'drs-next-btn'
        });

        // Create hint button if enabled
        if (this._config.showHints) {
            this._components.hintButton = componentRegistry.create('Button', {
                text: 'Hint',
                icon: '💡',
                type: 'outline',
                onClick: () => this._handleHint(),
                className: 'drs-hint-btn'
            });
        }

        // Create hint panel (initially hidden)
        this._components.hintPanel = componentRegistry.create('Panel', {
            title: 'Hint',
            type: 'hint',
            collapsible: true,
            collapsed: true,
            className: 'drs-hint-panel'
        });

        // Create result panel (initially hidden)
        this._components.resultPanel = componentRegistry.create('Panel', {
            title: 'Result',
            type: 'success',
            className: 'drs-result-panel'
        });

        // Assemble UI
        this._assembleUI();
    }

    /**
     * Assemble all UI components into the container
     */
    _assembleUI() {
        // Progress bar at top
        if (this._components.progressBar) {
            this._container.appendChild(this._components.progressBar.getElement());
        }

        // Main card
        this._container.appendChild(this._components.mainCard.getElement());

        // Action buttons container
        const actionsDiv = document.createElement('div');
        actionsDiv.className = 'drs-actions';
        actionsDiv.style.cssText = `
            display: flex;
            gap: 12px;
            margin-top: 16px;
            justify-content: space-between;
        `;

        // Left side: hint button
        if (this._components.hintButton) {
            actionsDiv.appendChild(this._components.hintButton.getElement());
        }

        // Right side: next button
        const rightActions = document.createElement('div');
        rightActions.style.cssText = 'margin-left: auto;';
        rightActions.appendChild(this._components.nextButton.getElement());
        actionsDiv.appendChild(rightActions);

        this._container.appendChild(actionsDiv);

        // Panels at bottom
        this._container.appendChild(this._components.hintPanel.getElement());
        this._container.appendChild(this._components.resultPanel.getElement());

        // Initially hide panels
        this._components.hintPanel.hide();
        this._components.resultPanel.hide();
    }

    /**
     * Show current exercise step
     */
    _showCurrentStep() {
        if (!this._currentExercise || !this._components.mainCard) return;

        const step = this._currentExercise.steps?.[this._currentStep] || this._currentExercise;
        console.log(`📖 Showing step ${this._currentStep + 1}/${this._totalSteps}:`, {
            id: step.id,
            type: step.type,
            hasContent: !!step.content,
            contentKeys: step.content ? Object.keys(step.content) : [],
            step: step
        });

        const progress = this.getProgress();

        // Update progress bar
        if (this._components.progressBar) {
            this._components.progressBar.setValue(this._currentStep + 1);
            this._components.progressBar.setLabel(`Step ${progress.currentStep} of ${progress.totalSteps}`);
        }

        // Update main card content
        const stepContent = this._generateStepContent(step);
        this._components.mainCard.setContent(stepContent);

        // Update next button text
        if (this._components.nextButton) {
            const isLast = this._currentStep === this._totalSteps - 1;
            this._components.nextButton.setText(isLast ? 'Finish' : 'Next');
        }

        // Hide result panel for new step
        if (this._components.resultPanel) {
            this._components.resultPanel.hide();
        }
    }

    /**
     * Generate HTML content for current step
     */
    _generateStepContent(step) {
        let content = '';

        // Step instruction
        if (step.instruction) {
            content += `<div class="drs-instruction">${step.instruction}</div>`;
        }

        // Content based on type
        if (step.type === 'text' || step.type === 'multiple-choice' || !step.type) {
            content += this._generateTextContent(step);
        } else if (step.type === 'audio') {
            content += this._generateAudioContent(step);
        } else if (step.type === 'image') {
            content += this._generateImageContent(step);
        } else if (step.type === 'grammar' || step.type === 'fill-blank') {
            content += this._generateGrammarContent(step);
        } else {
            // Fallback for unknown types
            console.warn(`⚠️ Unknown step type: ${step.type}, falling back to text`);
            content += this._generateTextContent(step);
        }

        return content;
    }

    /**
     * Generate text exercise content
     */
    _generateTextContent(step) {
        let content = `<div class="drs-text-content">`;

        // Use step.content if available (new format from ContentLoader)
        const stepData = step.content || step;

        // Show passage/text
        if (stepData.passage) {
            content += `<div class="drs-text-passage">${stepData.passage}</div>`;
        } else if (stepData.text) {
            content += `<div class="drs-text-passage">${stepData.text}</div>`;
        }

        // Show question
        if (stepData.question) {
            content += `<div class="drs-question">${stepData.question}</div>`;
        }

        // Show options (multiple choice)
        const options = stepData.options || step.options;
        if (options && options.length > 0) {
            console.log('🎯 Generating radio options:', options);
            content += `<div class="drs-options">`;
            options.forEach((option, index) => {
                content += `
                    <label class="drs-option">
                        <input type="radio" name="answer" value="${index}" required>
                        <span>${option}</span>
                    </label>
                `;
            });
            content += `</div>`;
        } else {
            console.warn('⚠️ No options found for multiple choice step:', step);
        }

        content += `</div>`;
        return content;
    }

    /**
     * Generate audio exercise content
     */
    _generateAudioContent(step) {
        let content = `<div class="drs-audio-content">`;

        if (step.audioUrl) {
            content += `
                <div class="drs-audio-player">
                    <audio controls>
                        <source src="${step.audioUrl}" type="audio/mpeg">
                        Your browser does not support audio playback.
                    </audio>
                </div>
            `;
        }

        if (step.transcript) {
            content += `<div class="drs-transcript" style="display: none;">${step.transcript}</div>`;
            content += `<button class="drs-show-transcript btn btn-secondary">Show Transcript</button>`;
        }

        if (step.question) {
            content += `<div class="drs-question">${step.question}</div>`;
        }

        content += `</div>`;
        return content;
    }

    /**
     * Generate image exercise content
     */
    _generateImageContent(step) {
        let content = `<div class="drs-image-content">`;

        if (step.imageUrl) {
            content += `
                <div class="drs-image-container">
                    <img src="${step.imageUrl}" alt="${step.description || 'Exercise image'}" class="drs-image">
                </div>
            `;
        }

        if (step.question) {
            content += `<div class="drs-question">${step.question}</div>`;
        }

        content += `</div>`;
        return content;
    }

    /**
     * Generate grammar exercise content
     */
    _generateGrammarContent(step) {
        let content = `<div class="drs-grammar-content">`;

        if (step.sentence) {
            // Fill-in-the-blank style
            const processedSentence = step.sentence.replace(/_+/g, '<input type="text" class="drs-blank">');
            content += `<div class="drs-sentence">${processedSentence}</div>`;
        }

        if (step.explanation) {
            content += `<div class="drs-explanation">${step.explanation}</div>`;
        }

        content += `</div>`;
        return content;
    }

    /**
     * Event handlers
     */
    _handleStart() {
        console.log('📢 DRS start event received');
    }

    _handleNext() {
        console.log('📋 Next button clicked');

        if (!this._isActive) {
            console.log('⚠️ DRS not active, ignoring next');
            return;
        }

        console.log(`Current step: ${this._currentStep}/${this._totalSteps}`);

        // Validate current step
        const isValid = this._validateCurrentStep();
        if (!isValid) {
            console.log('❌ Validation failed, showing error');
            this._showValidationError();
            return;
        }

        console.log('✅ Validation passed, moving to next step');

        // Move to next step or finish
        if (this._currentStep < this._totalSteps - 1) {
            // Emit step completed (for the step we just finished)
            this._eventBus.emit('drs:step-completed', {
                step: this._currentStep, // The step we just completed
                total: this._totalSteps
            }, this.name);

            this._currentStep++;
            this._showCurrentStep();
        } else {
            // Emit final step completed
            this._eventBus.emit('drs:step-completed', {
                step: this._currentStep,
                total: this._totalSteps
            }, this.name);

            this._finishExercise();
        }
    }

    _handleHint() {
        if (!this._components.hintPanel) return;

        const step = this._currentExercise.steps?.[this._currentStep] || this._currentExercise;

        if (step.hint) {
            this._components.hintPanel.setContent(step.hint);
            this._components.hintPanel.show();
            this._components.hintPanel.expand();

            // Track hint usage
            this._userProgress.hints++;

            // Emit hint used event
            this._eventBus.emit('drs:hint-used', {
                step: this._currentStep,
                hint: step.hint
            }, this.name);
        }
    }

    _handleSubmit(event) {
        console.log('📝 Submit event:', event);
        this._handleNext();
    }

    _handleContentLoaded(event) {
        console.log('📚 Content loaded event:', event);
    }

    /**
     * Validate current step input
     */
    _validateCurrentStep() {
        console.log('🔍 Validating current step...');

        // Basic validation - check for required inputs
        const inputs = this._container.querySelectorAll('input[required], input[type="radio"]');
        console.log(`Found ${inputs.length} inputs to validate`);

        if (inputs.length === 0) {
            console.log('✅ No validation needed');
            return true; // No validation needed
        }

        // Check radio buttons
        const radioGroups = this._container.querySelectorAll('input[type="radio"]');
        if (radioGroups.length > 0) {
            console.log(`Checking ${radioGroups.length} radio buttons...`);
            const groupNames = new Set();
            radioGroups.forEach(radio => groupNames.add(radio.name));

            for (const groupName of groupNames) {
                const checked = this._container.querySelector(`input[name="${groupName}"]:checked`);
                if (!checked) {
                    console.log(`❌ No radio button selected for group: ${groupName}`);
                    return false;
                }
                console.log(`✅ Radio group "${groupName}" has selection: ${checked.value}`);
            }
        }

        // Check text inputs
        const textInputs = this._container.querySelectorAll('input[required]:not([type="radio"])');
        if (textInputs.length > 0) {
            console.log(`Checking ${textInputs.length} text inputs...`);
            for (const input of textInputs) {
                if (!input.value.trim()) {
                    console.log(`❌ Required text input is empty: ${input.name || input.id}`);
                    return false;
                }
                console.log(`✅ Text input has value: ${input.value}`);
            }
        }

        console.log('✅ All validations passed');
        return true;
    }

    /**
     * Show validation error
     */
    _showValidationError() {
        if (this._components.resultPanel) {
            this._components.resultPanel.setType('warning');
            this._components.resultPanel.setContent('Please answer all questions before continuing.');
            this._components.resultPanel.show();

            setTimeout(() => {
                this._components.resultPanel.hide();
            }, 3000);
        }
    }

    /**
     * Finish exercise
     */
    _finishExercise() {
        this._isActive = false;

        // Calculate final stats
        this._userProgress.timeSpent = Date.now() - this._startTime;
        const finalStats = this.getProgress();

        // Show completion message
        if (this._components.resultPanel) {
            this._components.resultPanel.setType('success');
            this._components.resultPanel.setContent(`
                <h4>Exercise Complete!</h4>
                <p>Time spent: ${Math.round(finalStats.timeSpent / 1000)}s</p>
                <p>Hints used: ${this._userProgress.hints}</p>
            `);
            this._components.resultPanel.show();
        }

        // Hide next button
        if (this._components.nextButton) {
            this._components.nextButton.hide();
        }

        // Emit completion event
        this._eventBus.emit('drs:completed', {
            stats: finalStats,
            exercise: this._currentExercise
        }, this.name);

        console.log('🎉 Exercise completed!', finalStats);
    }

    /**
     * Clean up UI
     */
    _cleanupUI() {
        if (this._container) {
            this._container.innerHTML = '';
            this._container = null;
        }
        this._isActive = false;
    }
}

export default UnifiedDRS;