import React from 'react';
import MainContainer from '../MainContainer/MainContainer';
import { ResourcePicker } from '../ResourcePicker/ResourcePicker';
import {
    ResourceBrowserPlugin,
    ResourceBrowserSource,
    ResourceBrowserUnresolvedResource,
    ResourceBrowserResource,
    ResourceBrowserSourceWithPlugin,
    PluginLaunchMode,
    useResolveResourceResponse,
} from '../types';

export type ResourceBrowserInputProps = {
    modalTitle: string;
    allowedTypes?: string[];
    isDisabled?: boolean;
    value: ResourceBrowserUnresolvedResource | null;
    useResource(reference: ResourceBrowserUnresolvedResource | null, source: ResourceBrowserSource | null): useResolveResourceResponse;
    onChange(resource: ResourceBrowserResource | null): void;
    onClear?(): void;
    plugin: ResourceBrowserPlugin | null;
    pluginMode: PluginLaunchMode | null;
    searchEnabled: boolean;
    source: ResourceBrowserSource | null;
    sources: ResourceBrowserSourceWithPlugin[];
    isLoading: boolean;
    isOtherSourceValue: boolean;
    error: Error | null;
    setSource(source: ResourceBrowserSource, mode?: PluginLaunchMode): void;
    isModalOpen: boolean;
    onModalStateChange(isOpen: boolean): void;
};

export const ResourceBrowserInput = ({
    modalTitle,
    allowedTypes,
    onChange,
    value,
    useResource,
    isDisabled,
    onClear,
    plugin,
    pluginMode,
    searchEnabled,
    source,
    sources,
    isLoading,
    isOtherSourceValue,
    error,
    setSource,
    isModalOpen,
    onModalStateChange,
}: ResourceBrowserInputProps) => {
    const { data: resource, error: resourceError, isLoading: isResourceLoading } = useResource(value || null, source);

    const defaultOnClear = () => onChange(null);
    const onClearFunction = onClear ?? defaultOnClear;

    return (
        <ResourcePicker
            resource={resource}
            plugin={plugin}
            allowedTypes={allowedTypes}
            error={resourceError || error}
            isLoading={isResourceLoading || isLoading}
            isOtherSourceValue={isOtherSourceValue}
            isDisabled={isDisabled}
            onClear={onClearFunction}
            isModalOpen={isModalOpen}
            onModalStateChange={onModalStateChange}
        >
            {(onClose, titleProps) => (
                <MainContainer
                    selectedSource={source}
                    sources={sources}
                    preselectedResource={resource}
                    plugin={plugin}
                    pluginMode={pluginMode}
                    searchEnabled={searchEnabled}
                    title={modalTitle}
                    titleAriaProps={titleProps}
                    allowedTypes={allowedTypes}
                    onSourceSelect={setSource}
                    onClose={onClose}
                    onChange={onChange}
                />
            )}
        </ResourcePicker>
    );
};
