/**
 * External dependencies.
 */
import { useEffect } from '@wordpress/element';
import { useSelect, useDispatch } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import './editor.scss';

/**
 * Internal dependencies.
 */
import Render from './render';
import Settings from './settings';
import variations from './variations';
import RenderBlockPreview from '@spectra-components/render-block-preview';
import { VariationPicker } from '@spectra-components/variation-picker';
import blockIcons from '@spectra-pro-helpers/block-icons';


/**
 * The 'Edit' function.
 *
 * @since x.x.x
 *
 * @param {Object} props The element props.
 * @return {Element} Element to render.
 */
const Edit = ( props ) => {
	// Destructure the required props.
	const {
		clientId,
		name,
		isSelected,
		attributes: {
			isPreview,
			variationSelected,
		}
	} = props;

	// Get block variations and children.
	const {
		defaultVariation,
		blockChildren,
	} = useSelect( ( select ) => {
		// Use the selectors.
		const {
			getDefaultBlockVariation,
		} = select( 'core/blocks' );
		const {
			getBlocks,
		} = select( 'core/block-editor' );

		// Get the children (if any).
		const currentBlockChildren = getBlocks( clientId );

		// Return the required data.
		return {
			defaultVariation: getDefaultBlockVariation( name ),
			blockChildren: currentBlockChildren,
		};
	} );

	// Get the updateBlockAttributes dispatcher.
	const { updateBlockAttributes } = useDispatch( 'core/block-editor' );

	// Propagate variation selection to inner blocks when required.
	useEffect( () => {
		if ( variationSelected ) {
			blockChildren.forEach( ( child ) => {
				// Mark this child as the default selected variation if it is a container.
				if ( false === child.attributes?.variationSelected && 'spectra/container' === child.name ) {
					updateBlockAttributes( child.clientId, { variationSelected: true } );
				}
			} );
		}
	}, [ variationSelected, blockChildren ] );

	// If this is an example, return the preview image.
	if ( isPreview ) {
		return <RenderBlockPreview childPath="loop-builder-children" blockName="template" pluginName="spectra-pro" />;
	}

	// If there is no variation selected - render the variation picker.
	// Else just render the block render.
	return ( ! variationSelected ) ? (
		<VariationPicker { ...{
			...props,
			icon: blockIcons.loopBuilderChildren.template(),
			label: __( 'Loop Wrapper', 'spectra-pro' ),
			instructions: __( 'Select a variant to get started', 'spectra-pro' ),
			variations,
			defaultVariation,
		} } />
	) : (
		<>
			{ isSelected && <Settings { ...{ ...props } } /> }
			<Render { ...props } />
		</>
	);
};

export default Edit;
