import React, { forwardRef } from 'react';
import { ResourceBrowserInput, ResourceBrowserInputProps } from '../ResourceBrowserInput/ResourceBrowserInput';
import { ResourceBrowserInlineButton } from '../ResourceBrowserInlineButton/ResourceBrowserInlineButton';
import { AuthProvider } from '../ResourceBrowserContext/AuthProvider';
import { ResourceBrowserPluginType, InlineType, ResourceBrowserSourceWithConfig } from '../types';

/**
 *  This plugin component exsits to deal with React rules of Hooks stupidity.
 *
 *  For it to not freak out when we want to change from one plugin to another we have to render
 *  something to the ReactDom for each plugin and 'activate' that component when that plugin
 *  needs to render its UI etc.
 */
export type PluginRenderType = ResourceBrowserInputProps & {
    type: ResourceBrowserPluginType | null;
    render: boolean;
    inline: boolean;
    inlineType?: InlineType;
    onRetry: () => void;
    ref?: React.Ref<HTMLButtonElement>;
};
export const PluginRender = forwardRef<HTMLButtonElement, PluginRenderType>(({ render, inline, inlineType, ...props }, forwardRef) => {
    if (!render) return <></>;

    const requiresAuth =
        Boolean((props.source as ResourceBrowserSourceWithConfig)?.configuration?.authUrl) ||
        Boolean((props.source as ResourceBrowserSourceWithConfig)?.configuration?.alwaysUseResourceRequestProxy);

    const content =
        inline && inlineType ? (
            <ResourceBrowserInlineButton ref={forwardRef} inlineType={inlineType} {...props} />
        ) : (
            <ResourceBrowserInput {...props} />
        );

    return requiresAuth ? <AuthProvider authConfig={props.source}>{content}</AuthProvider> : content;
});
