import _ from 'lodash';
import { registerBlockType } from '@wordpress/blocks';
import { TextControl } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { useEntityProp } from '@wordpress/core-data';
import { useBlockProps } from '@wordpress/block-editor';

registerBlockType( 'bw/testimonials-meta-block', {
	edit: ( { setAttributes, attributes } ) => {
		const blockProps = useBlockProps();
		const postType = useSelect(
			( select ) => select( 'core/editor' ).getCurrentPostType(),
			[]
		);

		const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' );

		const updateMetaValue = (key) => ( newValue ) => {
			setMeta( { ...meta, [key]: newValue } );
		};

		return (
			<div { ...blockProps }>
				<TextControl
					label="Headline"
					value={ _.get( meta, 'headline' ) }
					onChange={ updateMetaValue(headline) }
				/>
				<TextControl
					label="Summary"
					value={ _.get( meta, 'summary' ) }
					onChange={ updateMetaValue(summary) }
				/>
				<TextControl
					label="Content"
					value={ _.get( meta, 'content' ) }
					onChange={ updateMetaValue(content) }
				/>
				<TextControl
					label="Author"
					value={ _.get( meta, 'author' ) }
					onChange={ updateMetaValue(author) }
				/>
				<TextControl
					label="Company"
					value={ _.get( meta, 'company' ) }
					onChange={ updateMetaValue(company) }
				/>
			</div>
		);
	},

	// No information saved to the block.
	// Data is saved to post meta via the hook.
	save: () => {
		return null;
	},
} );
