import type { Context, ExtensionDescriptor } from '@atlassian/clientside-extensions-registry';
import { onDebug } from '@atlassian/clientside-extensions-debug';
import React, { memo } from 'react';
import { useExtensionsAll } from './useExtensions';
import type { ExtensionPointCallback, Options } from './types';

export interface ExtensionPointProps {
    name: string;
    context?: Context<{}> | null;
    options: Options;
    children: ExtensionPointCallback<ExtensionDescriptor>;
}

const ExtensionPoint: React.FC<ExtensionPointProps> = ({ name, context = null, options, children }) => {
    const [supportedDescriptors, unsupportedDescriptors, isLoading] = useExtensionsAll(name, context, options);

    if (typeof children !== 'function') {
        onDebug(({ error }) => {
            return {
                level: error,

                message: `ExtensionPoint expects a render-child.\nThe "children"-property passed for extension point "${name}" is not a function.`,
                components: 'ExtensionPoint',
                meta: {
                    name,
                    context,
                    options,
                },
            };
        });
        return null;
    }

    return <>{children(supportedDescriptors, unsupportedDescriptors, isLoading)}</>;
};

export default memo(ExtensionPoint);
