import { PropsWithChildren, useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { IRootState } from './store';
import { toggleRTL, toggleTheme, toggleLocale, toggleMenu, toggleLayout, toggleAnimation, toggleNavbar, toggleSemidark } from './store/themeConfigSlice';
import store from './store';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { settingsService } from './services/settingsService';
import { useAuth } from './hooks/useAuth';
import { usePermissions } from './hooks/usePermissions';
function App({ children }: PropsWithChildren) {
    const { refreshPermissions } = usePermissions();
    const themeConfig = useSelector((state: IRootState) => state.themeConfig);
    const dispatch = useDispatch();
    const { token, isAuthenticated } = useAuth();
    const [settingsLoaded, setSettingsLoaded] = useState(true); // Start as true to avoid blocking

    useEffect(() => {
        dispatch(toggleTheme(localStorage.getItem('theme') || themeConfig.theme));
        dispatch(toggleMenu(localStorage.getItem('menu') || themeConfig.menu));
        dispatch(toggleLayout(localStorage.getItem('layout') || themeConfig.layout));
        dispatch(toggleRTL(localStorage.getItem('rtlClass') || themeConfig.rtlClass));
        dispatch(toggleAnimation(localStorage.getItem('animation') || themeConfig.animation));
        dispatch(toggleNavbar(localStorage.getItem('navbar') || themeConfig.navbar));
        dispatch(toggleLocale(localStorage.getItem('i18nextLng') || themeConfig.locale));
        dispatch(toggleSemidark(localStorage.getItem('semidark') || themeConfig.semidark));
    }, [dispatch]);

    // Fetch fresh settings on app load if user is authenticated
    useEffect(() => {
        const loadSettings = async () => {
            // Only fetch if user is authenticated and token exists
            if (token && isAuthenticated) {
                try {
                    setSettingsLoaded(false);
                    await settingsService.fetchAndUpdateSettings();
                } catch (error) {
                    console.error('Failed to load settings:', error);
                    // Don't block the app if settings fail to load
                    // Use existing settings from localStorage as fallback
                } finally {
                    setSettingsLoaded(true);
                }
            } else {
                setSettingsLoaded(true);
            }
        };
        refreshPermissions();
        loadSettings();
    }, [token, isAuthenticated]);

    // Don't block rendering, just show loading for a maximum of 2 seconds


    return (
        <div
            className={`${(store.getState().themeConfig.sidebar && 'toggle-sidebar') || ''} ${themeConfig.menu} ${themeConfig.layout} ${
                themeConfig.rtlClass
            } main-section antialiased relative font-nunito text-sm font-normal`}
        >
            {children}
            <ToastContainer
                position="top-right"
                autoClose={3000}
                hideProgressBar={false}
                newestOnTop
                closeOnClick
                pauseOnHover
                draggable
                theme={themeConfig.theme === 'dark' ? 'dark' : 'light'}
            />
        </div>
    );
}

export default App;
