import { useEffect, useMemo, useRef } from "react";

import { createPureScopedStylesheet } from "../createStylesheet.js";

import type { CreatePureScopedStylesheetCallbackArgs } from "../createStylesheet.js";

const usePureScopedStylesheet = <
    T extends Record<string, any> & {
        /**
         * A list of update keys which get mapped to `updateFromObject` and automatically
         * updates the stylesheet when changes are detected.
         */
        updater?: Record<string, (value: any) => any>;
    },
>(
    callback: (args: CreatePureScopedStylesheetCallbackArgs) => T,
    settings?: Parameters<typeof createPureScopedStylesheet>[1],
    updateFromObject?: { [P in keyof T["updater"]]?: any },
) => {
    const result = useMemo(() => createPureScopedStylesheet(callback, settings), []);
    const { updater } = result;

    if (updateFromObject && updater) {
        for (const k in updater) {
            const isFirstRun = useRef(true);
            useEffect(() => {
                if (isFirstRun.current) {
                    isFirstRun.current = false;
                    return;
                }

                updater[k]?.(updateFromObject[k]);
            }, [updateFromObject[k]]);
        }
    }

    useEffect(() => {
        result.toggle(true);
        return () => !settings?.reuse && result.toggle(false);
    }, []);

    return result;
};

export { usePureScopedStylesheet };
