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

import metadata from '../../../blocks/tags/product-price/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 } ) }
                        />
                    ) }
                    <SelectControl
                        label="Variable Product Price Format"
                        value={ attributes.variablePriceFormat }
                        options={ [
                            { label: 'From $X (lowest price)', value: 'from' },
                            { label: '$X - $Y (full range)', value: 'range' },
                        ] }
                        onChange={ ( val ) => setAttributes( { variablePriceFormat: val } ) }
                    />
                    { attributes.variablePriceFormat === 'from' && (
                        <TextControl
                            label="From Label Text"
                            value={ attributes.fromLabelText }
                            onChange={ ( val ) => setAttributes( { fromLabelText: val } ) }
                        />
                    ) }
                    { attributes.variablePriceFormat === 'range' && (
                        <TextControl
                            label="Range Separator"
                            value={ attributes.rangeSeparator }
                            onChange={ ( val ) => setAttributes( { rangeSeparator: val } ) }
                        />
                    ) }
                </PanelBody>
            </InspectorControls>
            <ServerSideRender
                block={ metadata.name }
                attributes={ attributes }
            />
        </>
    ),
    save: () => null,
} );
