import React from 'react';
import { StoryFn, Meta } from '@storybook/react';
import ResourceLauncher from './ResourceLauncher';
import sampleSources from '../__mocks__/sample-sources.json';
import { ResourceBrowserSourceWithPlugin, PluginLaunchMode, PluginLaunchModeType } from '../types';

const DummyLauncher = ({
    source,
    onSearch,
    onBrowse,
}: {
    source: any;
    onSearch: (query: string) => void;
    onBrowse: (browseTo: string) => void;
}) => (
    <div className="p-2 border rounded">
        <div>{source.name}</div>
        <button onClick={() => onSearch('sample query')} className="mr-2">
            Search
        </button>
        <button onClick={() => onBrowse('sample browse')}>Browse</button>
    </div>
);

const sourcesWithDummyPlugin = (sampleSources as any[]).map((source) => ({
    ...source,
    plugin: {
        ...source.plugin,
        type: source.plugin?.type || 'dummy',
        // renderResourceLauncher should return a component. Here we return a function that renders DummyLauncher.
        renderResourceLauncher: () => DummyLauncher,
    },
})) as ResourceBrowserSourceWithPlugin[];

export default {
    title: 'Resource Launcher',
    component: ResourceLauncher,
} as Meta<typeof ResourceLauncher>;

const Template: StoryFn<typeof ResourceLauncher> = (args) => {
    return (
        <div className="flex justify-center m-3">
            <ResourceLauncher
                {...args}
                sources={sourcesWithDummyPlugin}
                onSourceSelect={(source, mode: PluginLaunchMode) => {
                    console.log(`Source ${source?.name} / ${source.id} was selected with mode:`, mode);
                }}
            />
        </div>
    );
};

export const Primary = Template.bind({});
Primary.args = {};
