import { registerBlockType } from '@wordpress/blocks';
import { InspectorControls } from '@wordpress/block-editor';
import ServerSideRender from '@wordpress/server-side-render';
import { PanelBody, SelectControl } from '@wordpress/components';
import ProductSearchControl from '../../components/ProductSearchControl';

import metadata from '../../../blocks/tags/product-image/block.json';

registerBlockType( metadata.name, {
    edit: ( { attributes, setAttributes } ) => (
        <>
            <InspectorControls>
                <PanelBody title="Content">
                    <SelectControl
                        label="Product Source"
                        value={ attributes.productSource }
                        options={ [
                            { label: 'Current Product (Auto-detect)', value: 'current' },
                            { label: 'Select Product', value: 'custom' },
                        ] }
                        onChange={ ( val ) => setAttributes( { productSource: val } ) }
                    />
                    { attributes.productSource === 'custom' && (
                        <ProductSearchControl
                            value={ attributes.productId }
                            onChange={ ( val ) => setAttributes( { productId: val } ) }
                        />
                    ) }
                </PanelBody>
            </InspectorControls>
            <ServerSideRender
                block={ metadata.name }
                attributes={ attributes }
            />
        </>
    ),
    save: () => null,
} );
