import { PropsWithChildren, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import { IRootState } from './store';
import { toggleLocale, loadUserTheme, resetThemeToDefaults } from './store/themeConfigSlice';
import { setUser, setUserName, setUserEmail, setUserRole } from './store/userConfigSlice';
import { applyColorSchemeToDom, isLoggedInUserId } from './lib/theme-colors';
import themeConfig from './theme.config';

function App({ children }: PropsWithChildren) {
    const themeConfigState = useSelector((state: IRootState) => state.themeConfig);
    const userConfig = useSelector((state: IRootState) => state.userConfig);
    const dispatch = useDispatch();
    const { i18n } = useTranslation();

    // Hydrate user config once from localStorage
    useEffect(() => {
        dispatch(setUser(localStorage.getItem('user') || userConfig.user));
        dispatch(setUserName(localStorage.getItem('user_name') || userConfig.user_name));
        dispatch(setUserEmail(localStorage.getItem('user_email') || userConfig.user_email));
        dispatch(setUserRole(localStorage.getItem('role') || userConfig.role));
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [dispatch]);

    // Load per-user theme (or defaults when logged out)
    useEffect(() => {
        const userId = localStorage.getItem('user') || userConfig.user;
        if (isLoggedInUserId(userId)) {
            dispatch(loadUserTheme(userId));
        } else {
            dispatch(resetThemeToDefaults());
            applyColorSchemeToDom(themeConfig.colorScheme);
        }

        const locale = localStorage.getItem('i18nextLng') || themeConfigState.locale || themeConfig.locale;
        dispatch(toggleLocale(locale));
        i18n.changeLanguage(locale);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [dispatch, userConfig.user]);

    return (
        <div
            className={`${(themeConfigState.sidebar && 'toggle-sidebar') || ''} ${themeConfigState.menu} ${themeConfigState.layout} ${
                themeConfigState.rtlClass
            } main-section relative ${
                themeConfigState.colorScheme === 'neo' ? 'font-plex' : themeConfigState.colorScheme === 'xp' ? 'font-tahoma' : 'font-nunito'
            } text-sm font-normal antialiased`}
        >
            {children}
        </div>
    );
}

export default App;
