import { isNil } from 'lodash';
import { FC, ReactNode } from 'react';

import { useLifecycles } from 'react-use';

import { useThemeActions } from './hooks';
import { useThemeStore } from './store';
import { ThemeMode } from './types';

const Theme: FC<{ children?: ReactNode; mode?: `${ThemeMode}`; compact?: boolean }> = ({
    children,
    mode,
    compact,
}) => {
    const { changeMode, changeCompact } = useThemeActions();
    let unSub: () => void;
    useLifecycles(
        () => {
            useThemeStore.subscribe(
                (state) => state.mode,
                (m) => {
                    const body = document.getElementsByTagName('body');
                    if (body.length) {
                        body[0].classList.remove('light');
                        body[0].classList.remove('dark');
                        body[0].classList.add(m === 'dark' ? 'dark' : 'light');
                    }
                },
                {
                    fireImmediately: true,
                },
            );
        },
        () => {
            if (!isNil(unSub)) unSub();
        },
    );
    if (!isNil(mode)) changeMode(mode);
    if (!isNil(compact)) changeCompact(compact);

    return <>{children}</>;
};
export default Theme;
