const { registerPlugin } = wp.plugins;
const { PluginSidebar, PluginSidebarMoreMenuItem } = wp.editPost;
const { PanelBody, TextControl, TextareaControl } = wp.components;
const { withSelect, withDispatch } = wp.data;

const CustomSidebar = withSelect((select) => {
    return {
        audioLink: select('core/editor').getEditedPostAttribute('meta')['audio_link'] || '',
        videoLink: select('core/editor').getEditedPostAttribute('meta')['video_link'] || '',
        quoteText: select('core/editor').getEditedPostAttribute('meta')['quote_text'] || '',
        galleryImages: select('core/editor').getEditedPostAttribute('meta')['gallery_images'] || ''
    };
})(function ({ audioLink, videoLink, quoteText, galleryImages, dispatch }) {

    const onChangeAudioLink = (newAudioLink) => {
        dispatch('core/editor').editPost({ meta: { audio_link: newAudioLink } });
    };

    const onChangeVideoLink = (newVideoLink) => {
        dispatch('core/editor').editPost({ meta: { video_link: newVideoLink } });
    };

    const onChangeQuoteText = (newQuoteText) => {
        dispatch('core/editor').editPost({ meta: { quote_text: newQuoteText } });
    };

    const onChangeGalleryImages = (newGalleryImages) => {
        dispatch('core/editor').editPost({ meta: { gallery_images: newGalleryImages } });
    };

    return (
        <PluginSidebarMoreMenuItem target="custom-sidebar">
            Custom Sidebar
        </PluginSidebarMoreMenuItem>
    );
});

registerPlugin('custom-sidebar-plugin', {
    render: CustomSidebar,
    icon: 'admin-generic',
});

const SidebarControls = () => (
    <PluginSidebar name="custom-sidebar" title="Custom Sidebar">
        <PanelBody>
            <TextControl
                label="Audio Link"
                value={audioLink}
                onChange={onChangeAudioLink}
            />
            <TextControl
                label="Video Link"
                value={videoLink}
                onChange={onChangeVideoLink}
            />
            <TextareaControl
                label="Quote Text"
                value={quoteText}
                onChange={onChangeQuoteText}
            />
            <TextControl
                label="Gallery Images"
                value={galleryImages}
                onChange={onChangeGalleryImages}
            />
        </PanelBody>
    </PluginSidebar>
);

wp.domReady(() => {
    const el = wp.element.createElement;
    const { registerPlugin } = wp.plugins;
    registerPlugin('sidebar-controls', { render: SidebarControls });
});
