import { state } from '../state.js';
import * as THREE from 'three';
import { SceneFeature } from './SceneFeature.js';
import sceneFeatureManager from './SceneFeatureManager.js';
import { MediaStorage } from '../core/media-storage.js';
import { showStandbyScreen } from './projection-screen.js';
import { showToast } from '../core/ui-utils.js';
import { visualizerLibrary } from '../visualizers/index.js';

export class ConfigUI extends SceneFeature {
    constructor() {
        super();
        sceneFeatureManager.register(this);
        this.toggles = {};
        this.containers = [];
    }

    init() {
        // --- Left Panel: Party Schedule ---
        const leftContainer = document.createElement('div');
        leftContainer.id = 'config-ui-left';
        Object.assign(leftContainer.style, {
            position: 'absolute',
            top: '70px',
            left: '20px',
            zIndex: '1000',
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            padding: '15px',
            borderRadius: '8px',
            color: 'white',
            fontFamily: 'sans-serif',
            display: 'flex',
            flexDirection: 'column',
            gap: '10px',
            minWidth: '200px'
        });
        this.containers.push(leftContainer);

        const heading = document.createElement('h3');
        heading.innerText = 'Party schedule';
        Object.assign(heading.style, {
            margin: '0 0 15px 0',
            textAlign: 'center',
            borderBottom: '1px solid #555',
            paddingBottom: '10px'
        });
        leftContainer.appendChild(heading);

        // --- Right Panel: Party Venue ---
        const rightContainer = document.createElement('div');
        rightContainer.id = 'config-ui-right';
        Object.assign(rightContainer.style, {
            position: 'absolute',
            top: '70px',
            right: '20px',
            zIndex: '1000',
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            padding: '15px',
            borderRadius: '8px',
            color: 'white',
            fontFamily: 'sans-serif',
            display: 'flex',
            flexDirection: 'column',
            gap: '10px',
            minWidth: '200px'
        });
        this.containers.push(rightContainer);

        const venueHeading = document.createElement('h3');
        venueHeading.innerText = 'Party venue';
        Object.assign(venueHeading.style, {
            margin: '0 0 15px 0',
            textAlign: 'center',
            borderBottom: '1px solid #555',
            paddingBottom: '10px'
        });
        rightContainer.appendChild(venueHeading);

        const saveConfig = () => {
            localStorage.setItem('partyConfig', JSON.stringify(state.config));
        };

        const createToggle = (label, configKey, onChange) => {
            const row = document.createElement('div');
            row.style.display = 'flex';
            row.style.alignItems = 'center';
            row.style.justifyContent = 'space-between';

            const lbl = document.createElement('label');
            lbl.innerText = label;
            
            const chk = document.createElement('input');
            chk.type = 'checkbox';
            chk.checked = state.config[configKey];
            chk.style.cursor = 'pointer';
            chk.onchange = (e) => {
                state.config[configKey] = e.target.checked;
                saveConfig();
                if (onChange) onChange(e.target.checked);
            };

            this.toggles[configKey] = { checkbox: chk, callback: onChange };
            row.appendChild(lbl);
            row.appendChild(chk);
            rightContainer.appendChild(row);
        };

        // Debug Panel Toggle
        createToggle('Debug Panel', 'debugPanelEnabled', (enabled) => {
            const debugPanel = sceneFeatureManager.features.find(f => f.constructor.name === 'DebugPanel');
            if (debugPanel) debugPanel.setVisibility(enabled);
        });

        // Visualizer Selection
        const vizRow = document.createElement('div');
        vizRow.style.display = 'flex';
        vizRow.style.alignItems = 'center';
        vizRow.style.justifyContent = 'space-between';
        vizRow.style.marginTop = '10px';
        
        const vizLabel = document.createElement('label');
        vizLabel.innerText = 'Visualizer';
        
        const vizSelect = document.createElement('select');
        visualizerLibrary.forEach(viz => {
            const opt = document.createElement('option');
            opt.value = viz.getName();
            opt.innerText = viz.getName();
            if (opt.value === state.config.visualizerType) opt.selected = true;
            vizSelect.appendChild(opt);
        });
        vizSelect.onchange = (e) => {
            state.config.visualizerType = e.target.value;
            saveConfig();
        };
        vizRow.appendChild(vizLabel);
        vizRow.appendChild(vizSelect);
        rightContainer.appendChild(vizRow);

        // Visualizer Seed
        const seedRow = document.createElement('div');
        seedRow.style.display = 'flex';
        seedRow.style.alignItems = 'center';
        seedRow.style.justifyContent = 'space-between';
        
        const seedLabel = document.createElement('label');
        seedLabel.innerText = 'Visualizer Seed';
        
        const seedInput = document.createElement('input');
        seedInput.type = 'number';
        seedInput.step = '0.001';
        seedInput.value = state.config.visualizerSeed || 0;
        seedInput.style.width = '80px';
        seedInput.onchange = (e) => {
            state.config.visualizerSeed = parseFloat(e.target.value);
            saveConfig();
        };
        seedRow.appendChild(seedLabel);
        seedRow.appendChild(seedInput);
        rightContainer.appendChild(seedRow);

        // Blackout Toggle
        createToggle('BLACKOUT', 'blackout');

        // Torches Toggle
        createToggle('Stage Torches', 'torchesEnabled');

        // Lasers Toggle
        createToggle('Lasers', 'lasersEnabled');

        // Laser Color Mode
        const laserModeRow = document.createElement('div');
        laserModeRow.style.display = 'flex';
        laserModeRow.style.alignItems = 'center';
        laserModeRow.style.justifyContent = 'space-between';
        
        const laserModeLabel = document.createElement('label');
        laserModeLabel.innerText = 'Laser Colors';
        
        const laserModeSelect = document.createElement('select');
        ['SINGLE', 'RANDOM', 'RUNNING', 'ANY'].forEach(mode => {
            const opt = document.createElement('option');
            opt.value = mode;
            opt.innerText = mode.charAt(0) + mode.slice(1).toLowerCase();
            if (mode === state.config.laserColorMode) opt.selected = true;
            laserModeSelect.appendChild(opt);
        });
        laserModeSelect.onchange = (e) => {
            state.config.laserColorMode = e.target.value;
            saveConfig();
        };
        this.laserModeSelect = laserModeSelect;
        
        laserModeRow.appendChild(laserModeLabel);
        laserModeRow.appendChild(laserModeSelect);
        rightContainer.appendChild(laserModeRow);

        // Side Screens Toggle
        createToggle('Side Screens', 'sideScreensEnabled');

        // Music Console Toggle
        createToggle('Music Console', 'consoleEnabled', (enabled) => {
            const consoleFeature = sceneFeatureManager.features.find(f => f.constructor.name === 'MusicConsole');
            if (consoleFeature && consoleFeature.group) consoleFeature.group.visible = enabled;
        });

        // Console RGB Toggle
        createToggle('Console RGB Panel', 'consoleRGBEnabled');

        // Gameboy Toggle
        createToggle('Gameboy', 'gameboyEnabled');

        // Stage Light Bars Toggle
        createToggle('Stage Light Bars', 'lightBarsEnabled', (enabled) => {
            const lightBars = sceneFeatureManager.features.find(f => f.constructor.name === 'StageLightBars');
            if (lightBars) lightBars.setVisibility(enabled);
        });

        // --- Light Bar Colors ---
        const colorContainer = document.createElement('div');
        Object.assign(colorContainer.style, {
            display: 'flex',
            flexDirection: 'column',
            gap: '5px',
            marginTop: '5px',
            paddingTop: '5px',
            borderTop: '1px solid #444'
        });
        
        const colorLabel = document.createElement('label');
        colorLabel.innerText = 'Stage colors';
        colorContainer.appendChild(colorLabel);

        const colorControls = document.createElement('div');
        colorControls.style.display = 'flex';
        colorControls.style.gap = '5px';

        const colorPicker = document.createElement('input');
        colorPicker.type = 'color';
        colorPicker.value = '#ff00ff';
        colorPicker.style.width = '40px';
        colorPicker.style.border = 'none';
        colorPicker.style.cursor = 'pointer';
        
        const addColorBtn = document.createElement('button');
        addColorBtn.innerText = '+';
        addColorBtn.style.cursor = 'pointer';
        addColorBtn.onclick = () => {
            state.config.lightBarColors.push(colorPicker.value);
            saveConfig();
            this.updateColorList();
            const lightBars = sceneFeatureManager.features.find(f => f.constructor.name === 'StageLightBars');
            if (lightBars) lightBars.refreshColors();
        };

        const clearColorsBtn = document.createElement('button');
        clearColorsBtn.innerText = 'Clear';
        clearColorsBtn.style.cursor = 'pointer';
        clearColorsBtn.onclick = () => {
            state.config.lightBarColors = [];
            saveConfig();
            this.updateColorList();
            const lightBars = sceneFeatureManager.features.find(f => f.constructor.name === 'StageLightBars');
            if (lightBars) lightBars.refreshColors();
        };

        const randomizeColorsBtn = document.createElement('button');
        randomizeColorsBtn.innerText = 'Randomize';
        randomizeColorsBtn.style.cursor = 'pointer';
        randomizeColorsBtn.onclick = () => {
            const count = 2 + Math.floor(Math.random() * 5); // 2 to 6
            const newColors = [];
            for(let i=0; i<count; i++) {
                newColors.push('#' + new THREE.Color().setHSL(Math.random(), 1.0, 0.5).getHexString());
            }
            state.config.lightBarColors = newColors;
            saveConfig();
            this.updateColorList();
            const lightBars = sceneFeatureManager.features.find(f => f.constructor.name === 'StageLightBars');
            if (lightBars) lightBars.refreshColors();
        };

        colorControls.appendChild(colorPicker);
        colorControls.appendChild(addColorBtn);
        colorControls.appendChild(clearColorsBtn);
        colorControls.appendChild(randomizeColorsBtn);
        colorContainer.appendChild(colorControls);

        const colorList = document.createElement('div');
        colorList.style.display = 'flex';
        colorList.style.flexWrap = 'wrap';
        colorList.style.gap = '4px';
        colorList.style.marginTop = '4px';
        this.colorList = colorList;
        colorContainer.appendChild(colorList);
        rightContainer.appendChild(colorContainer);

        // Guest Count Input
        const guestRow = document.createElement('div');
        guestRow.style.display = 'flex';
        guestRow.style.alignItems = 'center';
        guestRow.style.justifyContent = 'space-between';
        
        const guestLabel = document.createElement('label');
        guestLabel.innerText = 'Guest Count';
        
        const guestInput = document.createElement('input');
        guestInput.type = 'number';
        guestInput.min = '0';
        guestInput.max = '500';
        guestInput.value = state.config.guestCount;
        guestInput.style.width = '60px';
        guestInput.onchange = (e) => {
            const val = parseInt(e.target.value, 10);
            state.config.guestCount = val;
            saveConfig();
            const guestsFeature = sceneFeatureManager.features.find(f => f.constructor.name === 'PartyGuests');
            if (guestsFeature) guestsFeature.setGuestCount(val);
        };
        this.guestInput = guestInput;

        guestRow.appendChild(guestLabel);
        guestRow.appendChild(guestInput);
        rightContainer.appendChild(guestRow);

        // DJ Hat Selector
        const hatRow = document.createElement('div');
        hatRow.style.display = 'flex';
        hatRow.style.alignItems = 'center';
        hatRow.style.justifyContent = 'space-between';
        
        const hatLabel = document.createElement('label');
        hatLabel.innerText = 'DJ Hat';
        
        const hatSelect = document.createElement('select');
        ['None', 'Santa', 'Top Hat'].forEach(opt => {
            const option = document.createElement('option');
            option.value = opt;
            option.innerText = opt;
            if (opt === state.config.djHat) option.selected = true;
            hatSelect.appendChild(option);
        });
        hatSelect.onchange = (e) => {
            state.config.djHat = e.target.value;
            saveConfig();
        };
        this.hatSelect = hatSelect;
        
        hatRow.appendChild(hatLabel);
        hatRow.appendChild(hatSelect);
        rightContainer.appendChild(hatRow);

        // --- Status & Control Section ---
        const statusContainer = document.createElement('div');
        Object.assign(statusContainer.style, {
            display: 'flex',
            flexDirection: 'column',
            gap: '8px'
        });

        // Loaded Song Label
        this.songLabel = document.createElement('div');
        this.songLabel.innerText = 'Song: (None)';
        this.songLabel.style.fontSize = '13px';
        this.songLabel.style.color = '#aaa';
        statusContainer.appendChild(this.songLabel);

        // Loaded Tapes List
        const tapesLabel = document.createElement('div');
        tapesLabel.innerText = 'Loaded Tapes:';
        tapesLabel.style.fontSize = '13px';
        statusContainer.appendChild(tapesLabel);

        this.tapeList = document.createElement('ul');
        Object.assign(this.tapeList.style, {
            margin: '0',
            paddingLeft: '20px',
            fontSize: '12px',
            color: '#aaa',
            maxHeight: '100px',
            overflowY: 'auto'
        });
        statusContainer.appendChild(this.tapeList);

        // Load Poster Button
        const loadPosterBtn = document.createElement('button');
        loadPosterBtn.innerText = 'Load Poster';
        Object.assign(loadPosterBtn.style, {
            marginTop: '10px',
            padding: '8px',
            cursor: 'pointer',
            backgroundColor: '#ff9800', // Default orange
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            fontSize: '14px'
        });
        
        const posterInput = document.createElement('input');
        posterInput.type = 'file';
        posterInput.accept = 'image/*';
        posterInput.style.display = 'none';
        posterInput.onchange = (e) => {
            const file = e.target.files[0];
            if (file) {
                if (state.posterImage) URL.revokeObjectURL(state.posterImage);
                state.posterImage = URL.createObjectURL(file);
                MediaStorage.savePoster(file);
                showStandbyScreen();
                this.updateStatus();
                showToast('Poster loaded', 'success');
            }
        };
        document.body.appendChild(posterInput);

        loadPosterBtn.onclick = () => {
            if (state.posterImage) {
                URL.revokeObjectURL(state.posterImage);
                state.posterImage = null;
                MediaStorage.deletePoster();
                showStandbyScreen();
                this.updateStatus();
                posterInput.value = '';
            } else {
                posterInput.click();
            }
        };
        this.loadPosterBtn = loadPosterBtn;
        statusContainer.appendChild(loadPosterBtn);

        // Load Tapes Button
        const loadTapesBtn = document.createElement('button');
        loadTapesBtn.id = 'loadTapeButton';
        loadTapesBtn.innerText = 'Load Tapes';
        Object.assign(loadTapesBtn.style, {
            marginTop: '10px',
            padding: '8px',
            cursor: 'pointer',
            backgroundColor: '#ff9800', // Default orange
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            fontSize: '14px'
        });
        statusContainer.appendChild(loadTapesBtn);
        state.loadTapeButton = loadTapesBtn;

        // Load Slideshow Button
        const loadSlideshowBtn = document.createElement('button');
        loadSlideshowBtn.innerText = 'Load Slideshow';
        Object.assign(loadSlideshowBtn.style, {
            marginTop: '10px',
            padding: '8px',
            cursor: 'pointer',
            backgroundColor: '#ff9800',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            fontSize: '14px'
        });
        
        const slideshowInput = document.createElement('input');
        slideshowInput.type = 'file';
        slideshowInput.multiple = true;
        slideshowInput.accept = 'image/*';
        slideshowInput.style.display = 'none';
        slideshowInput.onchange = (e) => {
            const files = Array.from(e.target.files);
            if (files.length > 0) {
                if (state.imageUrls) state.imageUrls.forEach(url => URL.revokeObjectURL(url));
                state.imageUrls = files.map(f => URL.createObjectURL(f));
                state.imageFilenames = files.map(f => f.name);
                state.isSlideshowLoaded = true;
                this.updateStatus();
                showToast(`Loaded ${files.length} images`, 'success');
            }
        };
        document.body.appendChild(slideshowInput);
        loadSlideshowBtn.onclick = () => slideshowInput.click();
        this.loadSlideshowBtn = loadSlideshowBtn;
        statusContainer.appendChild(loadSlideshowBtn);

        // Choose Song Button
        const chooseSongBtn = document.createElement('button');
        chooseSongBtn.innerText = 'Choose Song';
        Object.assign(chooseSongBtn.style, {
            marginTop: '10px',
            padding: '8px',
            cursor: 'pointer',
            backgroundColor: '#ff9800', // Default orange
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            fontSize: '14px'
        });
        chooseSongBtn.onclick = () => {
            const fileInput = document.getElementById('musicFileInput');
            if (fileInput) fileInput.click();
        };
        this.chooseSongBtn = chooseSongBtn;
        statusContainer.appendChild(chooseSongBtn);

        // Start Party Button
        this.startButton = document.createElement('button');
        this.startButton.innerText = 'Start the Party';
        this.startButton.disabled = true;
        Object.assign(this.startButton.style, {
            marginTop: '10px',
            padding: '10px',
            cursor: 'not-allowed',
            backgroundColor: '#dc3545', // Default red
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            fontSize: '16px',
            fontWeight: 'bold'
        });
        
        this.startButton.onclick = () => {
            const musicPlayer = sceneFeatureManager.features.find(f => f.constructor.name === 'MusicPlayer');
            if (musicPlayer) musicPlayer.startSequence();
        };
        statusContainer.appendChild(this.startButton);
        leftContainer.appendChild(statusContainer);

        // Reset Button
        const resetBtn = document.createElement('button');
        resetBtn.innerText = 'Reset Defaults';
        Object.assign(resetBtn.style, {
            marginTop: '10px',
            padding: '8px',
            cursor: 'pointer',
            backgroundColor: '#555',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            fontSize: '14px'
        });
        resetBtn.onclick = () => {
            localStorage.removeItem('partyConfig');
            MediaStorage.clear();

            // Clear State - Video
            if (state.videoUrls) {
                state.videoUrls.forEach(url => URL.revokeObjectURL(url));
            }
            state.videoUrls = [];
            state.videoFilenames = [];
            state.isVideoLoaded = false;
            state.currentVideoIndex = -1;
            if (state.imageUrls) {
                state.imageUrls.forEach(url => URL.revokeObjectURL(url));
            }
            state.imageUrls = [];
            state.imageFilenames = [];
            state.isSlideshowLoaded = false;
            if (state.loadTapeButton) {
                state.loadTapeButton.innerText = 'Load Tapes';
                state.loadTapeButton.classList.remove('hidden');
            }

            // Clear State - Music
            if (state.music) {
                state.music.songTitle = null;
                if (state.music.player) {
                    state.music.player.pause();
                    state.music.player.removeAttribute('src');
                    state.music.player.load();
                }
            }

            if (state.posterImage) {
                URL.revokeObjectURL(state.posterImage);
                state.posterImage = null;
            }

            showStandbyScreen();

            const defaults = {
                torchesEnabled: true,
                lasersEnabled: true,
                sideScreensEnabled: true,
                consoleRGBEnabled: true,
                consoleEnabled: true,
                gameboyEnabled: false,
                lightBarsEnabled: true,
                laserColorMode: 'RUNNING',
                guestCount: 150,
                blackout: true,
                djHat: 'None',
                debugPanelEnabled: false,
                visualizerType: 'Classic Wave',
                visualizerSeed: Math.random() * 1000
            };
            for (const key in defaults) {
                state.config[key] = defaults[key];
                if (this.toggles[key]) {
                    this.toggles[key].checkbox.checked = defaults[key];
                    if (this.toggles[key].callback) this.toggles[key].callback(defaults[key]);
                }
            }
            if (this.guestInput) this.guestInput.value = defaults.guestCount;
            if (this.laserModeSelect) this.laserModeSelect.value = defaults.laserColorMode;
            if (this.hatSelect) this.hatSelect.value = defaults.djHat;
            this.updateStatus();
        };
        leftContainer.appendChild(resetBtn);

        document.body.appendChild(leftContainer);
        document.body.appendChild(rightContainer);
        this.updateStatus();
        this.updateColorList();

        // Restore poster
        MediaStorage.getPoster().then(file => {
            if (file) {
                state.posterImage = URL.createObjectURL(file);
                showStandbyScreen();
                this.updateStatus();
            }
        });
    }

    updateColorList() {
        if (!this.colorList) return;
        this.colorList.innerHTML = '';
        state.config.lightBarColors.forEach(color => {
            const swatch = document.createElement('div');
            Object.assign(swatch.style, {
                width: '15px',
                height: '15px',
                backgroundColor: color,
                border: '1px solid #fff',
                borderRadius: '2px'
            });
            this.colorList.appendChild(swatch);
        });
    }

    updateStatus() {
        if (!this.songLabel) return;

        const orange = '#ff9800';
        const green = '#28a745';
        const red = '#dc3545';

        // Update Song Info
        if (state.music && state.music.songTitle) {
            this.songLabel.innerText = `Song: ${state.music.songTitle}`;
            this.songLabel.style.color = '#fff';
            
            this.startButton.disabled = false;
            this.startButton.style.backgroundColor = green;
            this.startButton.style.color = 'white';
            this.startButton.style.cursor = 'pointer';
            this.startButton.style.opacity = '1';
            
            if (this.chooseSongBtn) this.chooseSongBtn.style.backgroundColor = green;
        } else {
            this.songLabel.innerText = 'Song: (None)';
            this.songLabel.style.color = '#aaa';
            
            this.startButton.disabled = true;
            this.startButton.style.backgroundColor = red;
            this.startButton.style.color = 'white';
            this.startButton.style.opacity = '0.6';
            this.startButton.style.cursor = 'not-allowed';

            if (this.chooseSongBtn) this.chooseSongBtn.style.backgroundColor = orange;
        }

        if (this.loadPosterBtn) {
            this.loadPosterBtn.style.backgroundColor = state.posterImage ? green : orange;
            this.loadPosterBtn.innerText = state.posterImage ? 'Clear Poster' : 'Load Poster';
        }
        if (state.loadTapeButton) {
            const hasTapes = state.videoUrls && state.videoUrls.length > 0;
            state.loadTapeButton.style.backgroundColor = hasTapes ? green : orange;
            state.loadTapeButton.innerText = hasTapes ? 'Change Tapes' : 'Load Tapes';
        }
        if (this.loadSlideshowBtn) {
            const hasImages = state.imageUrls && state.imageUrls.length > 0;
            this.loadSlideshowBtn.style.backgroundColor = hasImages ? green : orange;
            this.loadSlideshowBtn.innerText = hasImages ? 'Change Slideshow' : 'Load Slideshow';
        }

        // Update Media List
        this.tapeList.innerHTML = '';
        if (state.videoUrls && state.videoUrls.length > 0) {
            state.videoUrls.forEach((url, index) => {
                const li = document.createElement('li');
                let name = `Tape ${index + 1}`;
                if (state.videoFilenames && state.videoFilenames[index]) {
                    name = state.videoFilenames[index];
                }
                
                if (name.length > 25) {
                    li.innerText = name.substring(0, 22) + '...';
                    li.title = name;
                } else {
                    li.innerText = name;
                }
                this.tapeList.appendChild(li);
            });
        }
        
        if (state.imageUrls && state.imageUrls.length > 0) {
            state.imageUrls.forEach((url, index) => {
                const li = document.createElement('li');
                let name = `Image ${index + 1}`;
                if (state.imageFilenames && state.imageFilenames[index]) {
                    name = state.imageFilenames[index];
                }
                
                if (name.length > 25) {
                    li.innerText = name.substring(0, 22) + '...';
                    li.title = name;
                } else {
                    li.innerText = name;
                }
                this.tapeList.appendChild(li);
            });
        }

        if ((!state.videoUrls || state.videoUrls.length === 0) && (!state.imageUrls || state.imageUrls.length === 0)) {
            const li = document.createElement('li');
            li.innerText = '(No media loaded)';
            this.tapeList.appendChild(li);
        }
    }

    onPartyStart() {
        this.containers.forEach(c => c.style.display = 'none');
    }

    onPartyEnd() {
        this.containers.forEach(c => c.style.display = 'flex');
    }
}