import { ReactNode, useRef, useLayoutEffect } from 'react';

import { globalStyles, createTheme } from '../../stitches.config';

export interface ThemeProps {
    /** Content to use as the theme */
    children: ReactNode;

    /** Theme to use for the components */
    theme?: ReturnType<typeof createTheme>;

    /** Apply the reset CSS */
    reset?: boolean;

    /** Element to apply the theme to */
    root?: HTMLElement;
}

export const Theme = (props: ThemeProps): JSX.Element => {
    const { children, theme = createTheme({}), reset = true, root } = props;

    // apply the reset
    if (reset) {
        globalStyles();
    }

    // refs
    const rootRef = useRef<HTMLElement | null>(null);
    const themeRef = useRef<ReturnType<typeof createTheme> | null>(null);

    // add the theme to the root element if it exists
    useLayoutEffect(() => {
        // remove the theme
        if (rootRef.current && themeRef.current) {
            rootRef.current.classList.remove(themeRef.current);
        }

        // save it
        rootRef.current = root || document.body;
        themeRef.current = theme;

        // add the class
        rootRef.current.classList.add(themeRef.current);
    }, [root, theme]);

    return <>{children}</>;
};
