import { createLogger } from '../shared/logger.js';

const logger = createLogger('legacy-connect');
/**
 * 连接界面逻辑
 * 处理初始连接、创建通话和加入通话的功能
 */

import { showNotification, randomMeetingId } from '../shared/utils.js';

const MAX_AVATAR_SIZE = 2 * 1024 * 1024; // 2MB

// 加入通话
function joinCall() {
    const connectionId = document.getElementById('connectionIdInput').value.trim();
    if (connectionId) {
        showNotification(`正在加入通话 (${connectionId})`);

        // 保存连接ID到本地存储
        localStorage.setItem('connectionId', connectionId);

        // 跳转到通话界面
        window.location.href = '/';
    } else {
        showNotification('请输入连接ID', 'error');
    }
}

// 创建通话
function createCall() {
    showNotification('正在创建通话...');

    // 生成随机连接ID
    //const connectionId = 'conn_' + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
    const connectionId = randomMeetingId();
    showNotification(`已创建通话 (${connectionId})`);
    
    // 保存连接ID到本地存储
    localStorage.setItem('connectionId', connectionId);

    // 跳转到通话界面
    window.location.href = '/';
}


// 获取所有连接ID
async function getAllConnectionIds() {
    showNotification('正在获取连接ID列表...');
    try {
        const response = await fetch('/signaling/connection-ids');
        if (!response.ok) {
            throw new Error('Failed to fetch connection IDs');
        }
        const data = await response.json();
        displayConnectionIds(data.connectionIds);
    } catch (error) {
        logger.error('Error fetching connection IDs:', error);
        showNotification('获取连接ID失败', 'error');
    }
}

// 显示连接ID列表
function displayConnectionIds(connectionIds) {
    const idsContainer = document.getElementById('idsContainer');
    const connectionIdsList = document.getElementById('connectionIdsList');

    if (idsContainer) {
        // 清空容器
        idsContainer.innerHTML = '';

        if (connectionIds.length === 0) {
            idsContainer.innerHTML = '<p class="text-gray-500 text-sm">暂无可用的连接ID</p>';
        } else {
            // 为每个连接ID创建一个元素
            connectionIds.forEach(id => {
                const idElement = document.createElement('div');
                idElement.className = 'flex items-center justify-between p-2 bg-white/5 rounded-lg hover:bg-white/10 cursor-pointer transition-colors';
                idElement.innerHTML = `
                    <span class="text-sm">${id}</span>
                    <button class="text-xs bg-indigo-600 hover:bg-indigo-700 px-2 py-1 rounded" onclick="selectConnectionId('${id}')">选择</button>
                `;
                idsContainer.appendChild(idElement);
            });
        }

        // 显示连接ID列表
        if (connectionIdsList) {
            connectionIdsList.classList.remove('hidden');
        }

        showNotification(`找到 ${connectionIds.length} 个连接ID`);
    }
}

// 选择连接ID
function selectConnectionId(id) {
    const connectionIdInput = document.getElementById('connectionIdInput');
    if (connectionIdInput) {
        connectionIdInput.value = id;
        showNotification(`已选择连接ID: ${id}`);
    }
}

// 绑定事件监听器
function bindEvents() {
    // 连接按钮
    const connectBtn = document.getElementById('connectBtn');
    if (connectBtn) {
        connectBtn.addEventListener('click', joinCall);
    }

    // 创建通话按钮
    const createCallBtn = document.getElementById('createCallBtn');
    if (createCallBtn) {
        createCallBtn.addEventListener('click', createCall);
    }

    // 浏览全部ID按钮
    const browseIdsBtn = document.getElementById('browseIdsBtn');
    if (browseIdsBtn) {
        browseIdsBtn.addEventListener('click', getAllConnectionIds);
    }

    // 输入框回车事件
    const connectionIdInput = document.getElementById('connectionIdInput');
    if (connectionIdInput) {
        connectionIdInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                joinCall();
            }
        });
    }
}

// 生成8位的用户ID
function generateUserId() {
    // 生成8位随机字符串，包含字母和数字
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = 'user_';
    for (let i = 0; i < 8; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
}

// 加载用户设置
function loadUserSettings() {
    const defaultAvatar = '/images/p1.png';
    const userSettings = localStorage.getItem('userSettings');
    if (userSettings) {
        try {
            const settings = JSON.parse(userSettings);

            // 设置用户ID
            if (settings.userId) {
                document.getElementById('userIdInput').value = settings.userId;
            }

            // 设置昵称
            if (settings.name) {
                document.getElementById('nicknameInput').value = settings.name;
                document.getElementById('userName').textContent = settings.name;
            }

            // 设置头像
            const avatar = settings.avatar || defaultAvatar;
            document.getElementById('userAvatar').src = avatar;
            document.getElementById('avatarPreview').src = avatar;
        } catch (error) {
            logger.error('Error loading user settings:', error);
            // 加载失败时使用默认头像
            const defaultAvatar = '/images/p1.png';
            document.getElementById('userAvatar').src = defaultAvatar;
            document.getElementById('avatarPreview').src = defaultAvatar;
        }
    } else {
        // 生成新的用户ID
        const newUserId = generateUserId();
        document.getElementById('userIdInput').value = newUserId;

        // 使用默认头像
        const defaultAvatar = '/images/p1.png';
        document.getElementById('userAvatar').src = defaultAvatar;
        document.getElementById('avatarPreview').src = defaultAvatar;

        // 保存默认设置
        saveSettings();
    }
}

// 保存用户设置
function saveSettings() {
    const defaultAvatar = '/images/p1.png';
    const settings = {
        userId: document.getElementById('userIdInput').value,
        name: document.getElementById('nicknameInput').value || '我',
        avatar: document.getElementById('avatarPreview').src || defaultAvatar
    };

    localStorage.setItem('userSettings', JSON.stringify(settings));

    // 更新界面显示
    document.getElementById('userName').textContent = settings.name;
    document.getElementById('userAvatar').src = settings.avatar;

    showNotification('设置已保存', 'success');
}

// 处理头像上传
function handleAvatarUpload(event) {
    const file = event.target.files[0];
    if (file) {
        // 检查文件类型
        if (!file.type.startsWith('image/')) {
            showNotification('请选择图片文件', 'error');
            return;
        }

        // 检查文件大小
        if (file.size > MAX_AVATAR_SIZE) { // 2MB限制
            showNotification('图片大小不能超过2MB', 'error');
            return;
        }

        // 创建FormData对象
        const formData = new FormData();
        formData.append('avatar', file);
        formData.append('userId', document.getElementById('userIdInput').value);

        // 显示上传中通知
        showNotification('正在上传头像...');

        // 上传头像到服务器
        fetch('/api/upload/avatar', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('上传失败');
            }
            return response.json();
        })
        .then(data => {
            if (data.success && data.avatarUrl) {
                // 更新预览和本地存储
                const avatarUrl = data.avatarUrl;
                document.getElementById('avatarPreview').src = avatarUrl;
                document.getElementById('userAvatar').src = avatarUrl;

                // 保存设置
                saveSettings();

                showNotification('头像上传成功', 'success');
            } else {
                throw new Error('上传失败：' + (data.message || '未知错误'));
            }
        })
        .catch(error => {
            logger.error('Error uploading avatar:', error);
            showNotification('头像上传失败，请重试', 'error');

            // 上传失败时，使用默认头像
            const defaultAvatar = '/images/p1.png';
            document.getElementById('avatarPreview').src = defaultAvatar;
        });
    }
}

// 复制用户ID到剪贴板
function copyUserId() {
    const userIdInput = document.getElementById('userIdInput');
    userIdInput.select();
    document.execCommand('copy');
    showNotification('用户ID已复制到剪贴板', 'success');
}

// 切换设置菜单
function toggleSettingsMenu() {
    const settingsMenu = document.getElementById('settingsMenu');
    settingsMenu.classList.toggle('hidden');
}

// 点击外部关闭设置菜单
document.addEventListener('click', function(event) {
    const settingsMenu = document.getElementById('settingsMenu');
    const userSettingsBtn = document.getElementById('userSettingsBtn');

    if (!settingsMenu.contains(event.target) && !userSettingsBtn.contains(event.target)) {
        settingsMenu.classList.add('hidden');
    }
});

// 绑定用户设置相关事件
function bindUserSettingsEvents() {
    // 设置按钮点击事件
    const userSettingsBtn = document.getElementById('userSettingsBtn');
    if (userSettingsBtn) {
        userSettingsBtn.addEventListener('click', toggleSettingsMenu);
    }
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', () => {
    bindEvents();
    bindUserSettingsEvents();

    // 检查本地存储中是否有连接ID
    const savedConnectionId = localStorage.getItem('connectionId');
    if (savedConnectionId) {
        const connectionIdInput = document.getElementById('connectionIdInput');
        if (connectionIdInput) {
            connectionIdInput.value = savedConnectionId;
        }
    }

    // 加载用户设置
    loadUserSettings();
});

// 导出全局函数
window.joinCall = joinCall;
window.createCall = createCall;
window.selectConnectionId = selectConnectionId;
window.saveSettings = saveSettings;
window.handleAvatarUpload = handleAvatarUpload;
window.copyUserId = copyUserId;
window.toggleSettingsMenu = toggleSettingsMenu;
