/**
 * External dependencies
 */
import { __ } from '@wordpress/i18n';
import { InnerBlocks } from '@wordpress/block-editor';
import { registerBlockType } from '@wordpress/blocks';
import { Icon, grid } from '@kkart/icons';
import '@kkart/atomic-blocks';

/**
 * Internal dependencies
 */
import Editor from './edit';
import { attributes as sharedAttributes, defaults } from '../attributes';
import { getBlockClassName } from '../utils.js';

const blockSettings = {
	title: __( 'All Products', 'kkart' ),
	icon: {
		src: <Icon srcElement={ grid } />,
		foreground: '#96588a',
	},
	category: 'kkart',
	keywords: [ __( 'Kkart', 'kkart' ) ],
	description: __(
		'Display products from your store in a grid layout.',
		'kkart'
	),
	supports: {
		align: [ 'wide', 'full' ],
		html: false,
		multiple: false,
	},
	example: {
		attributes: {
			isPreview: true,
		},
	},
	attributes: sharedAttributes,
	defaults,
	/**
	 * Renders and manages the block.
	 *
	 * @param {Object} props Props to pass to block.
	 */
	edit( props ) {
		return <Editor { ...props } />;
	},
	// Save the props to post content.
	save( { attributes } ) {
		const dataAttributes = {};
		Object.keys( attributes )
			.sort()
			.forEach( ( key ) => {
				dataAttributes[ key ] = attributes[ key ];
			} );
		const data = {
			'data-attributes': JSON.stringify( dataAttributes ),
		};
		return (
			<div
				className={ getBlockClassName(
					'kkart-block-all-products',
					attributes
				) }
				{ ...data }
			>
				<InnerBlocks.Content />
			</div>
		);
	},
};

/**
 * Register and run the "All Products" block.
 */
registerBlockType( 'kkart/all-products', {
	...blockSettings,
	/**
	 * Deprecation rule to handle the previous default rows which was 1 instead of 3.
	 */
	deprecated: [
		{
			attributes: Object.assign( {}, blockSettings.attributes, {
				rows: { type: 'number', default: 1 },
			} ),
			save( { attributes } ) {
				const data = {
					'data-attributes': JSON.stringify( attributes ),
				};
				return (
					<div
						className={ getBlockClassName(
							'kkart-block-all-products',
							attributes
						) }
						{ ...data }
					>
						<InnerBlocks.Content />
					</div>
				);
			},
		},
	],
} );
