import { showNotification } from '../shared/utils.js';
import store from './store.js';
import {
    fetchConnectionDirectory,
    fetchOnlineUsers,
    renderConnectionIds,
    renderOnlineUsers
} from './signaling/connect-directory.js';
import { createProfileSettingsController } from './controllers/profile-settings.js';
import { createLogger } from '../shared/logger.js';

const logger = createLogger('connectview');

let onWsStatusChange = null;
let cachedOnlineUsers = [];

const profileSettingsController = createProfileSettingsController({
    store,
    notify: showNotification
});

export function setWsStatusCallback(callback) {
    onWsStatusChange = callback;
}

export function updateWsStatus(connected) {
    const wsStatusDot = document.getElementById('wsStatusDot');
    const wsStatusText = document.getElementById('wsStatusText');

    if (wsStatusDot && wsStatusText) {
        if (connected) {
            wsStatusDot.className = 'w-2 h-2 bg-green-500 rounded-full animate-pulse';
            wsStatusText.textContent = 'WebSocket已连接';
        } else {
            wsStatusDot.className = 'w-2 h-2 bg-gray-500 rounded-full';
            wsStatusText.textContent = '未连接';
        }
    }

    if (onWsStatusChange) {
        onWsStatusChange(connected);
    }
}

export async function initWebSocket() {
    try {
        await store.connectSignaling();
        store.syncSocketUserInfo();
        updateWsStatus(true);
        await refreshOnlineUsers();
        logger.debug('WebSocket initialized from connectview');
    } catch (error) {
        logger.error('Failed to initialize WebSocket:', error);
        updateWsStatus(false);
        showNotification('WebSocket连接失败，请刷新页面重试', 'error');
    }
}

async function refreshOnlineUsers(silent = true) {
    try {
        cachedOnlineUsers = await fetchOnlineUsers();
        updateOnlineUsersList(cachedOnlineUsers);

        if (!silent) {
            showNotification(`当前共有 ${cachedOnlineUsers.length} 个WebSocket用户在线`);
        }
    } catch (error) {
        logger.error('Error fetching online users:', error);
        if (!silent) {
            showNotification('获取在线用户失败', 'error');
        }
    }
}

async function getAllConnectionIds() {
    showNotification('正在获取连接ID和在线用户...');

    try {
        const { connectionIds, users } = await fetchConnectionDirectory();
        cachedOnlineUsers = users;
        updateConnectionIdList(connectionIds);
        updateOnlineUsersList(cachedOnlineUsers);
    } catch (error) {
        logger.error('Error fetching connection IDs:', error);
        showNotification('获取连接信息失败', 'error');
    }
}

function updateConnectionIdList(connectionIds) {
    const idsContainer = document.getElementById('idsContainer');
    const connectionIdsList = document.getElementById('connectionIdsList');

    renderConnectionIds({
        connectionIds,
        idsContainer,
        connectionIdsList,
        onSelectConnectionId: selectConnectionId
    });

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

function getCurrentUserId() {
    try {
        const settings = JSON.parse(localStorage.getItem('userSettings') || '{}');
        return settings.userId || settings.id || '';
    } catch (error) {
        logger.error('Error parsing current user settings:', error);
        return '';
    }
}

function updateOnlineUsersList(users) {
    const onlineUsersList = document.getElementById('onlineUsersList');
    const usersContainer = document.getElementById('usersContainer');
    const onlineUsersSummary = document.getElementById('onlineUsersSummary');

    renderOnlineUsers({
        users,
        currentUserId: getCurrentUserId(),
        onlineUsersList,
        usersContainer,
        onlineUsersSummary
    });
}

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

export function loadUserSettings() {
    profileSettingsController.loadUserSettings();
}

export function saveSettings() {
    profileSettingsController.saveSettings();
}

export function handleAvatarUpload(event) {
    profileSettingsController.handleAvatarUpload(event);
}

export function copyUserId() {
    profileSettingsController.copyUserId();
}

export function toggleSettingsMenu() {
    profileSettingsController.toggleSettingsMenu();
}

export function bindConnectViewEvents(onJoinCall, onCreateCall) {
    const connectBtn = document.getElementById('connectBtn');
    if (connectBtn && !connectBtn.dataset.bound) {
        connectBtn.addEventListener('click', () => {
            const connectionIdInput = document.getElementById('connectionIdInput');
            const connectionId = connectionIdInput ? connectionIdInput.value.trim() : '';

            if (connectionId) {
                onJoinCall(connectionId);
            } else {
                showNotification('请输入连接ID', 'error');
            }
        });
        connectBtn.dataset.bound = 'true';
    }

    const createCallBtn = document.getElementById('createCallBtn');
    if (createCallBtn && !createCallBtn.dataset.bound) {
        createCallBtn.addEventListener('click', onCreateCall);
        createCallBtn.dataset.bound = 'true';
    }

    const browseIdsBtn = document.getElementById('browseIdsBtn');
    if (browseIdsBtn && !browseIdsBtn.dataset.bound) {
        browseIdsBtn.addEventListener('click', getAllConnectionIds);
        browseIdsBtn.dataset.bound = 'true';
    }

    const connectionIdInput = document.getElementById('connectionIdInput');
    if (connectionIdInput && !connectionIdInput.dataset.bound) {
        connectionIdInput.addEventListener('keypress', (event) => {
            if (event.key !== 'Enter') {
                return;
            }

            const connectionId = connectionIdInput.value.trim();
            if (connectionId) {
                onJoinCall(connectionId);
            } else {
                showNotification('请输入连接ID', 'error');
            }
        });
        connectionIdInput.dataset.bound = 'true';
    }

    const userSettingsBtn = document.getElementById('userSettingsBtn');
    if (userSettingsBtn && !userSettingsBtn.dataset.bound) {
        userSettingsBtn.addEventListener('click', toggleSettingsMenu);
        userSettingsBtn.dataset.bound = 'true';
    }
}

profileSettingsController.bindDocumentEvents();
profileSettingsController.bindWindowHandlers();
window.selectConnectionId = selectConnectionId;
