import { useDispatch, useSelector } from 'react-redux';
import AppRouter from './router/router';
import { checkAuthThunk } from './store/auth/auth.thunk';
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { login } from './store/auth/auth.slice';
import { initWebSocket, closeWebSocket } from './services/websocket';
import { setWebSocketConnected } from './store/notificationCenter/notificationCenter.slice';

function App() {
    const navigate = useNavigate();
    const dispatch = useDispatch();

    const { user } = useSelector((state) => state.auth);
    const { isConnected } = useSelector((state) => state.notificationCenter);

    // 检查用户认证状态
    useEffect(() => {
        handleCheckAuth();
    }, [dispatch]);

    // 管理WebSocket连接
    useEffect(() => {
        console.log(user, isConnected);
        
        // 如果用户已认证但WebSocket未连接，则初始化连接
        if (user && !isConnected) {
            initWebSocket()
                .then(() => {
                    // dispatch(setWebSocketConnected(true));
                    // console.log('WebSocket connection initialized');
                })
                .catch((error) => {
                    console.error('Failed to initialize WebSocket connection:', error);
                });
        }

        // 组件卸载或用户登出时关闭WebSocket连接
        return () => {
            if (isConnected) {
                closeWebSocket();
                dispatch(setWebSocketConnected(false));
            }
        };
    }, [user, isConnected, dispatch]);

    const handleCheckAuth = async () => {
        console.log('app handleCheckAuth');
        try {
            await dispatch(checkAuthThunk()).unwrap();
            if (!user) navigate('/login');
        } catch (error) {
            console.log('error', error);
            navigate('/login');
        }
    };

    return <AppRouter></AppRouter>;
}

export default App;
