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

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 = (): JSX.Element => {
    const navigate = useNavigate();
    const location = useLocation();
    const chatRef = useRef<ConversationHandle>(null);
    const submitQuery = (query: ChatQuery): void => {
        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 />}
                        />
                        {/* Static/shared routes */}
                        <Route
                            path="/*"
                            element={
                                <BackstoryLayout
                                    {...{ page, chatRef, submitQuery }}
                                />
                            }
                        />
                    </Routes>
                </AppStateProvider>
            </AuthProvider>
        </ThemeProvider>
    );
};

export { BackstoryApp };
