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

const Edit = ({ attributes, setAttributes }) => {
    const { text, url } = attributes;

    // Set home URL as default on first render if url is empty.
    useEffect(() => {
        if (!url && typeof memberpressBlocks !== 'undefined' && memberpressBlocks.homeUrl) {
            setAttributes({ url: memberpressBlocks.homeUrl });
        }
    }, []);

    const blockProps = useBlockProps({
        className: 'mepr-back-link has-text-align-center'
    });

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Link Settings', 'memberpress')}>
                    <TextControl
                        label={__('URL', 'memberpress')}
                        value={url}
                        onChange={(value) => setAttributes({ url: value })}
                        help={__('Leave empty to use home URL', 'memberpress')}
                    />
                </PanelBody>
            </InspectorControls>
            <p {...blockProps}>
                <a href={url || '#'} onClick={(e) => e.preventDefault()}>
                    <RichText
                        tagName="span"
                        value={text}
                        onChange={(value) => setAttributes({ text: value })}
                        placeholder={__('Back to home', 'memberpress')}
                        allowedFormats={[]}
                    />
                </a>
            </p>
        </>
    );
};

const Save = () => {
    return null;
};

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