import {
    useImperativeHandle,
    type ReactNode,
    forwardRef,
    useEffect,
    useState
} from "react";
import {
    StyleSheet,
    View
} from "react-native";
import {
    context
} from "./context";

export interface IManagerHandles {
    update(key?: string, children?: ReactNode, name?: string): void;
    mount(key: string, children: ReactNode, name?: string): void;
    unmount(key?: string): void;
}

export const Manager = forwardRef(({
    name
}: {
    name?: string;
}, ref): Array<ReactNode> => {
    const [
        portals,
        setPortals
    ] = useState<Array<{
        children: ReactNode;
        name?: string;
        key: string;
    }>>([]);

    useEffect(() => {
        return context.subscribe((newPortals) => {
            setPortals(newPortals);
        });
    }, []);

    useImperativeHandle(
        ref,
        (): IManagerHandles => ({
            unmount: context.unmount,
            update: context.update,
            mount: context.mount
        }),
    );

    return portals
        .filter(item => {
            if (item.name) {
                return item.name === name;
            }

            return !name;
        })
        .map((
            {
                children,
                key
            },
            index: number
        ) => (
            <View
                key={`NCoreUIKit-Portal-${key}-${index}`}
                style={[
                    StyleSheet.absoluteFill,
                    {
                        pointerEvents: "box-none"
                    }
                ]}
                collapsable={false}
            >
                {children}
            </View>
        ));
});
