import { registerBlockType } from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import { SelectControl, PanelBody, TextControl } from '@wordpress/components';
import { defaultBlock } from '../../icons';
import metadata from './block.json';

const Edit = ({ attributes, setAttributes }) => {
        const { field, label } = attributes;
    const blockProps = useBlockProps({
        className: `mepr-thank-you-order-value mepr-val-${field}`
    });

        return (
            <>
                <InspectorControls>
                    <PanelBody title={__("Settings", "memberpress")}>
                        <SelectControl
                            label={__("Field", "memberpress")}
                            value={field}
                            options={[
                                { label: __("Order Number", "memberpress"), value: 'order_number' },
                                { label: __("Amount", "memberpress"), value: 'amount' },
                                { label: __("Date", "memberpress"), value: 'date' }
                            ]}
                            onChange={(val) => setAttributes({ field: val })}
                        />
                        <TextControl
                            label={__("Label", "memberpress")}
                            value={label}
                            onChange={(val) => setAttributes({ label: val })}
                            placeholder={__("e.g. Order:", "memberpress")}
                        />
                    </PanelBody>
                </InspectorControls>
                <div {...blockProps}>
                    {label && <span className="mepr-order-value-label" style={{ marginRight: '5px' }}>{label}</span>}
                    <span className="mepr-order-value-data">
                        {`[${field.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}]`}
                    </span>
                </div>
            </>
        );
};

const Save = () => {
        return null; // Server-side rendered
};

registerBlockType(metadata.name, {
    ...metadata,
    icon: defaultBlock,
    edit: Edit,
    save: Save
});
