import React, { useEffect, useState } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { setUpToken, clearToken } from './utils/auth'; // Import the token utilities

import ResponsiveAppBar from './components/ResponsiveAppBar';
import ShipmentView from './pages/ShipmentView';
import HomePage from './pages/HomeView';
import ResultsView from './pages/ResultsView';
import PlanningView from './pages/PlanningView';
import Modal from './components/Modal';
import AddressManager from './pages/AddressManagerView';
import ContactsManager from './pages/ContactsManagerView';
import LoginView from './pages/LoginView';
import ProtectedRoute from './components/ProtectedRoute';
import BeamtimeOverview from './components/BeamtimeOverview';

const App: React.FC = () => {
    const [openAddressManager, setOpenAddressManager] = useState(false);
    const [openContactsManager, setOpenContactsManager] = useState(false);

    const handleOpenAddressManager = () => setOpenAddressManager(true);
    const handleCloseAddressManager = () => setOpenAddressManager(false);
    const handleOpenContactsManager = () => setOpenContactsManager(true);
    const handleCloseContactsManager = () => setOpenContactsManager(false);

    const [pgroups, setPgroups] = useState<string[]>([]);
    const [activePgroup, setActivePgroup] = useState<string>('');

    // On app load, configure the token
    useEffect(() => {
        setUpToken(); // Ensure token is loaded into OpenAPI on app initialization
    }, []);

    useEffect(() => {
        const updateStateFromLocalStorage = () => {
            const user = localStorage.getItem('user');
            console.log("[DEBUG] User data in localStorage (update):", user); // Debug
            if (user) {
                try {
                    const parsedUser = JSON.parse(user);
                    if (parsedUser.pgroups && Array.isArray(parsedUser.pgroups)) {
                        setPgroups(parsedUser.pgroups);
                        setActivePgroup(parsedUser.pgroups[0] || '');
                        console.log("[DEBUG] Pgroups updated in state:", parsedUser.pgroups);
                    } else {
                        console.warn("[DEBUG] No pgroups found in user data");
                    }
                } catch (error) {
                    console.error("[DEBUG] Error parsing user data:", error);
                }
            } else {
                console.warn("[DEBUG] No user in localStorage");
            }
        };

        // Run on component mount
        updateStateFromLocalStorage();

        // Listen for localStorage changes
        window.addEventListener('storage', updateStateFromLocalStorage);

        // Cleanup listener on unmount
        return () => {
            window.removeEventListener('storage', updateStateFromLocalStorage);
        };
    }, []);

    const handlePgroupChange = (newPgroup: string) => {
        setActivePgroup(newPgroup);
        console.log(`pgroup changed to: ${newPgroup}`);
    };

    return (
        <Router>
            <ResponsiveAppBar
                activePgroup={activePgroup}
                onOpenAddressManager={handleOpenAddressManager}
                onOpenContactsManager={handleOpenContactsManager}
                pgroups={pgroups || []} // Default to an empty array
                currentPgroup={activePgroup}
                onPgroupChange={handlePgroupChange}
            />
            <Routes>
                <Route path="/login" element={<LoginView />} />
                <Route path="/" element={<ProtectedRoute element={<HomePage />} />} />
                <Route path="/shipments" element={<ProtectedRoute element={<ShipmentView pgroups={pgroups} activePgroup={activePgroup} />} />} />
                <Route path="/planning" element={<ProtectedRoute element={<PlanningView />} />} />
                <Route path="/results/:beamtimeId" element={<ProtectedRoute element={<ResultsView pgroups={pgroups} activePgroup={activePgroup} />} />} />
                <Route path="/beamtime-overview" element={<ProtectedRoute element={<BeamtimeOverview activePgroup={activePgroup} />} />} />
                <Route path="/results" element={<ProtectedRoute element={<BeamtimeOverview activePgroup={activePgroup} />} />}/>
                {/* Optionally, add a 404 fallback route */}
                <Route path="*" element={<div>Page not found</div>} />

            </Routes>
            <Modal open={openAddressManager} onClose={handleCloseAddressManager} title="Address Management">
                <AddressManager pgroups={pgroups} activePgroup={activePgroup} />
            </Modal>
            <Modal open={openContactsManager} onClose={handleCloseContactsManager} title="Contacts Management">
                <ContactsManager pgroups={pgroups} activePgroup={activePgroup} />
            </Modal>
        </Router>
    );
};

export default App;