export default class RemoteDesktop {
    constructor(os) {
        this.os = os;
        this.element = document.getElementById('remote-desktop');
        this.closeBtn = this.element.querySelector('.close-btn');
        this.connectBtn = this.element.querySelector('#rd-connect-btn');
        this.disconnectBtn = this.element.querySelector('#rd-disconnect-btn');
        this.peerIdInput = this.element.querySelector('#rd-peer-id');
        this.statusIndicator = this.element.querySelector('#rd-status');
        this.statusText = this.element.querySelector('#rd-status-text');
        this.connectionList = this.element.querySelector('#rd-connection-list');

        this.isConnected = false;
        this.currentPeerId = null;
        this.recentConnections = [];

        this.initialize();
    }

    initialize() {
        this.closeBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.os.closeAllPopups();
        });

        this.connectBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.connectToPeer();
        });

        this.disconnectBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.disconnect();
        });

        this.peerIdInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                e.stopPropagation();
                this.connectToPeer();
            }
        });

        // Listen for status updates from Tauri backend
        this.listenForEvents();
    }

    async listenForEvents() {
        if (window.__TAURI__) {
            const { listen } = await import('@tauri-apps/api/event');

            await listen('rustdesk-status', (event) => {
                const { running, pid } = event.payload;
                this.updateStatus(running, pid);
            });

            await listen('rustdesk-connected', (event) => {
                const { peer_id, pid } = event.payload;
                this.onConnected(peer_id, pid);
            });
        }
    }

    async connectToPeer() {
        const peerId = this.peerIdInput.value.trim();
        if (!peerId) {
            this.setStatus('error', 'Please enter a peer ID');
            return;
        }

        this.setStatus('connecting', `Connecting to ${peerId}...`);
        this.connectBtn.disabled = true;

        try {
            if (window.__TAURI__) {
                const { invoke } = await import('@tauri-apps/api/core');
                const result = await invoke('connect_to_peer', { peerId });

                if (result.running) {
                    this.currentPeerId = peerId;
                    this.addToRecent(peerId);
                    this.onConnected(peerId, result.pid);
                } else {
                    this.setStatus('error', 'Failed to start RustDesk');
                    this.connectBtn.disabled = false;
                }
            } else {
                // Fallback for non-Tauri environments
                this.setStatus('error', 'RustDesk requires Tauri runtime');
                this.connectBtn.disabled = false;
            }
        } catch (err) {
            console.error('RustDesk connection error:', err);
            this.setStatus('error', `Connection failed: ${err}`);
            this.connectBtn.disabled = false;
        }
    }

    async disconnect() {
        try {
            if (window.__TAURI__) {
                const { invoke } = await import('@tauri-apps/api/core');
                await invoke('stop_rustdesk');
            }
        } catch (err) {
            console.error('RustDesk stop error:', err);
        }

        this.isConnected = false;
        this.currentPeerId = null;
        this.setStatus('disconnected', 'Disconnected');
        this.connectBtn.disabled = false;
    }

    async startRustdesk() {
        try {
            if (window.__TAURI__) {
                const { invoke } = await import('@tauri-apps/api/core');
                const result = await invoke('start_rustdesk');
                this.updateStatus(result.running, result.pid);
                return result;
            }
        } catch (err) {
            console.error('RustDesk start error:', err);
            this.setStatus('error', `Failed to start: ${err}`);
        }
        return null;
    }

    onConnected(peerId, pid) {
        this.isConnected = true;
        this.currentPeerId = peerId;
        this.setStatus('connected', `Connected to ${peerId} (PID: ${pid})`);
        this.connectBtn.disabled = true;
    }

    updateStatus(running, pid) {
        if (running) {
            this.setStatus('connected', `RustDesk running (PID: ${pid})`);
            this.isConnected = true;
        } else {
            this.setStatus('disconnected', 'RustDesk not running');
            this.isConnected = false;
            this.currentPeerId = null;
            this.connectBtn.disabled = false;
        }
    }

    setStatus(state, text) {
        this.statusIndicator.className = 'rd-status-indicator';
        this.statusIndicator.classList.add(`rd-status-${state}`);
        this.statusText.textContent = text;

        if (state === 'connected') {
            this.disconnectBtn.style.display = 'flex';
            this.connectBtn.style.display = 'none';
        } else {
            this.disconnectBtn.style.display = 'none';
            this.connectBtn.style.display = 'flex';
        }
    }

    addToRecent(peerId) {
        // Remove duplicate if exists
        this.recentConnections = this.recentConnections.filter(id => id !== peerId);
        // Add to front
        this.recentConnections.unshift(peerId);
        // Keep only last 5
        if (this.recentConnections.length > 5) {
            this.recentConnections = this.recentConnections.slice(0, 5);
        }
        this.renderRecentConnections();
    }

    renderRecentConnections() {
        this.connectionList.innerHTML = '';

        if (this.recentConnections.length === 0) {
            this.connectionList.innerHTML = `
                <div class="rd-empty-recent">
                    <span class="material-icons">history</span>
                    <span>No recent connections</span>
                </div>
            `;
            return;
        }

        const fragment = document.createDocumentFragment();

        this.recentConnections.forEach(peerId => {
            const item = document.createElement('div');
            item.className = 'rd-recent-item';
            item.innerHTML = `
                <div class="rd-recent-info">
                    <span class="material-icons rd-recent-icon">computer</span>
                    <div class="rd-recent-details">
                        <span class="rd-recent-id">${peerId}</span>
                        <span class="rd-recent-label">Remote Desktop</span>
                    </div>
                </div>
                <button class="rd-recent-connect">
                    <span class="material-icons">play_arrow</span>
                </button>
            `;

            const connectBtn = item.querySelector('.rd-recent-connect');
            connectBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                this.peerIdInput.value = peerId;
                this.connectToPeer();
            });

            fragment.appendChild(item);
        });

        this.connectionList.appendChild(fragment);
    }

    open() {
        this.element.classList.add('active');
        this.os.components.taskbar.updateActiveButton('remoteDesktop');
        this.renderRecentConnections();

        // Check current status
        if (window.__TAURI__) {
            import('@tauri-apps/api/core').then(({ invoke }) => {
                invoke('get_rustdesk_status').then(result => {
                    this.updateStatus(result.running, result.pid);
                }).catch(() => {});
            });
        }
    }

    close() {
        this.element.classList.remove('active');
        this.os.components.taskbar.updateActiveButton(null);
    }
}
