import React, { Suspense, useCallback } from 'react';
import env from '../env';
import useWS from './useWS';
import AdvancedWebSocket from './advanced-websocket';
import { Route, Routes } from 'react-router-dom';
import Navbar from './nav';
import {handleResponse, websocketRequest} from './socket-handlers';
import { useAppContext } from './app';

const Home: React.FC = () => {
    const {flash, logout} = useAppContext() as any
    const { ws } = useWS(env.WS_HOST, (data: any, ws: AdvancedWebSocket | null) => {
        if (!ws) return
        handleResponse(data, ({ type, data, error }) => {
            if (error) {
                flash(error)
                if (type === 'auth' && error !== 'Timeout') {
                    logout()
                }
            } else {
                console.log({ type, data })
            }
        })
    })
    const sendRequest = useCallback((type: string, data: any) => {
        if (!ws) return Promise.reject(new Error('No WS'))
        return websocketRequest(ws, type, data)
    }, [ws])
    return (
        <div className={`flex flex-col transition-all duration-300 h-full w-full overflow-x-hidden overflow-y-auto`}>
            <Suspense fallback={<div>Loading...</div>}>
                <div className="flex-1 flex flex-col">
                    <Navbar />
                    <Routes>
                        <Route path="*" element={<div>404 Not Found</div>} />
                    </Routes>
                </div>
            </Suspense>
        </div>
    );
};

export default Home;