/**
 * Retrieves the translation of text.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-i18n/
 */
import { __ } from '@wordpress/i18n';

/**
 * React hook that is used to mark the block wrapper element.
 * It provides all the necessary props like the class name.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-block-editor/#useblockprops
 */
import { useBlockProps } from '@wordpress/block-editor';
import { TextControl, CheckboxControl } from '@wordpress/components';
import { useEffect } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';


/**
 * 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 {WPElement} Element to render.
 */
export default function Edit( { attributes, setAttributes } ) {
	const { title, productAttributes, selectedAttributes } = attributes;

	useEffect( () => {
		apiFetch( { path: '/wc/v3/products/attributes' } ).then( ( productAttributes ) => {
			setAttributes( { productAttributes } );
		} );
	}, [] );

	const onChangeAttribute = ( checked, attribute ) => {
		if ( checked ) {
			setAttributes( { selectedAttributes: [ ...selectedAttributes, attribute.id ] } );
		} else {
			setAttributes( { selectedAttributes: selectedAttributes.filter( ( item ) => item !== attribute.id ) } );
		}
	};

	console.log( productAttributes );

	return (
		<div { ...useBlockProps() }>
			<TextControl
				label={ __( 'Title', 'wcvendors-pro' ) }
				onChange={ ( title ) => setAttributes( { title } ) }
				value={ title }
			/>

			{ productAttributes && productAttributes.map( ( attribute ) => {
				return (
					<CheckboxControl
						label={ attribute.name }
						checked={ selectedAttributes.includes( attribute.id ) }
						onChange={ ( checked ) => onChangeAttribute( checked, attribute ) }
					/>
				);
			} ) }

		</div>
	);
}
