import React, { useEffect, useState } from 'react';
import { Route, Routes, useLocation } from 'react-router-dom';
import StationIntroPage from './pages/StationIntroPage/StationIntroPage.jsx';
import ShowQueuesForTellerPage from './pages/ShowQueuesForTellerPage/ShowQueuesForTellerPage';
import Header from './components/Header/Header.jsx';
import CurrentTicketPage from './pages/CurrentTicketPage/CurrentTicketPage.jsx';
import BranchDisplayPage from './pages/BranchDisplayPage/BranchDisplayPage.jsx';
import LoginPage from './pages/LoginPage/LoginPage.jsx';
import AuthGuard from './components/AuthGuard/AuthGuard.jsx';
import { UserContext } from './context/UserContext.jsx';
import { clearSession, getToken, getUserData } from './utils/session.js';
import { SERVER_URL } from './constants.js';
import { fetchData } from './fetching/Fetch.js';

export default function App() {
    const [user, setUser] = useState(() => getUserData());
    const location = useLocation();
    const isDisplayRoute = location.pathname.startsWith('/display');

    useEffect(() => {
        document.body.classList.toggle('display-mode', isDisplayRoute);
        return () => document.body.classList.remove('display-mode');
    }, [isDisplayRoute]);

    useEffect(() => {
        const token = getToken();
        if (!token) {
            return;
        }

        fetchData(`${SERVER_URL}/api/v1/auth`, 'GET').then(({ success }) => {
            if (success) {
                setUser(getUserData());
            } else {
                clearSession();
                setUser(null);
            }
        });
    }, []);

    return (
        <UserContext.Provider value={{ user, setUser }}>
            {isDisplayRoute ? null : <Header />}
            <Routes>
                <Route exact path="/login" element={<LoginPage />} />
                <Route
                    exact
                    path="/"
                    element={
                        <AuthGuard>
                            <StationIntroPage />
                        </AuthGuard>
                    }
                />
                <Route
                    exact
                    path="/teller-queue/:stationId"
                    element={
                        <AuthGuard>
                            <ShowQueuesForTellerPage />
                        </AuthGuard>
                    }
                />
                {/* Public display boards for waiting area screens */}
                <Route
                    path="/display/branch/:tenantCode/:branchId"
                    element={<BranchDisplayPage />}
                />
                <Route path="/display/:stationId" element={<CurrentTicketPage />} />
            </Routes>
        </UserContext.Provider>
    );
}
