import { InspectorControls, useBlockProps } from '@wordpress/block-editor';

/**
 * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.
 * Those files can contain any CSS code that gets applied to the editor.
 *
 * @see https://www.npmjs.com/package/@wordpress/scripts#using-css
 */
import { useEffect } from 'react';
import { dispatch } from '@wordpress/data';
import './editor.scss';
import MultistepLeadFormBlock from './components/multistep-lead-form-block';
import BlockSettings from './components/settings/block-settings';

/**
 * The edit function describes the structure of your block in the context of the
 * editor. This represents what the editor will render when the block is used.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit

 * @return {Element} Element to render.
 */
export default function Edit({ attributes, setAttributes }) {
    const questionLockPrefix = 'question-lock-';
    const onBlockRemoveHandler = () => {
        const steps = attributes.steps || [];

        steps.forEach(step => {
            const questionLockName = questionLockPrefix + step.id;

            dispatch('core/notices').removeNotice(questionLockName);
        });
    };

    useEffect(() => {
        return onBlockRemoveHandler;
    }, []);

    return (
        <div { ...useBlockProps() }>
            <MultistepLeadFormBlock
                attributes={ attributes }
                setAttributes={ setAttributes }
                questionLockPrefix={ questionLockPrefix }
            />
            <InspectorControls key="setting">
                <BlockSettings
                    attributes={ attributes }
                    setAttributes={ setAttributes }
                />
            </InspectorControls>
        </div>
    );
}
