import React, { useEffect, useState, useRef, useCallback } from 'react';
import { Route, Routes, useLocation, useNavigate } from 'react-router-dom';
import { ThemeProvider } from '@mui/material/styles';
import { backstoryTheme } from './BackstoryTheme';

import { SeverityType } from 'components/Snack';
import { ConversationHandle } from 'components/Conversation';
import { CandidateRoute } from 'routes/CandidateRoute';
import { BackstoryLayout } from 'components/layout/BackstoryLayout';
import { ChatQuery } from 'types/types';
import { AuthProvider } from 'hooks/AuthContext';
import { AppStateProvider } from 'hooks/GlobalContext';

import './BackstoryApp.css';
import '@fontsource/roboto/300.css';
import '@fontsource/roboto/400.css';
import '@fontsource/roboto/500.css';
import '@fontsource/roboto/700.css';

const BackstoryApp = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const snackRef = useRef<any>(null);
    const chatRef = useRef<ConversationHandle>(null);
    const setSnack = useCallback((message: string, severity?: SeverityType) => {
        snackRef.current?.setSnack(message, severity);
    }, [snackRef]);
    const submitQuery = (query: ChatQuery) => {
        console.log(`handleSubmitChatQuery:`, query, chatRef.current ? ' sending' : 'no handler');
        chatRef.current?.submitQuery(query);
        navigate('/chat');
    };
    const [page, setPage] = useState<string>("");

    useEffect(() => {
        const currentRoute = location.pathname.split("/")[1] ? `/${location.pathname.split("/")[1]}` : "/";
        setPage(currentRoute);
    }, [location.pathname]);

    // Render appropriate routes based on user type
    return (
        <ThemeProvider theme={backstoryTheme}>
            <AuthProvider>
                <AppStateProvider>
                    <Routes>
                        <Route path="/u/:username" element={<CandidateRoute {...{ setSnack }} />} />
                        {/* Static/shared routes */}
                        <Route
                            path="/*"
                            element={
                                <BackstoryLayout {...{ setSnack, page, chatRef, snackRef, submitQuery }} />
                            }
                        />
                    </Routes>
                </AppStateProvider>
            </AuthProvider>
        </ThemeProvider>
    );
};

export {
  BackstoryApp
};