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

import metadata from '../../../blocks/premium/compare-icon/block.json';

registerBlockType( metadata.name, {
    edit: ( { attributes, setAttributes } ) => (
        <>
            <InspectorControls>
                <PanelBody title="Content">
                    <ProductSearchControl
                        value={ attributes.productId }
                        onChange={ ( val ) => setAttributes( { productId: val } ) }
                    />
                    <ToggleControl
                        label="Show Count"
                        checked={ attributes.showCount === 'yes' }
                        onChange={ ( val ) => setAttributes( { showCount: val ? 'yes' : '' } ) }
                    />
                    <ToggleControl
                        label="Link to Comparison Page"
                        checked={ attributes.linkToCompare === 'yes' }
                        onChange={ ( val ) => setAttributes( { linkToCompare: val ? 'yes' : '' } ) }
                    />
                    { attributes.linkToCompare === 'yes' && (
                        <TextControl
                            label="Comparison Page URL"
                            value={ attributes.comparePageUrl }
                            onChange={ ( val ) => setAttributes( { comparePageUrl: val } ) }
                            help="Leave empty to use the default comparison page."
                        />
                    ) }
                </PanelBody>
            </InspectorControls>
            <ServerSideRender block={ metadata.name } attributes={ attributes } />
        </>
    ),
    save: () => null,
} );
