import React from 'react';
import fetch from 'unfetch';
const { upperFirst, kebabCase } = window.lodash;
const { Fragment } = wp.element;
const { dispatch, select } = wp.data;
const { PanelBody, Button, Dashicon } = wp.components;
const { __ } = wp.i18n;

// const { data, apiFetch } = wp;
// const { registerStore } = data;

// import { dispatch as dataDispatch, select as dataSelect } from '@wordpress/data';

const { getSelectedBlock, getCurrentPostId } = select( 'core/editor' );

const {
	insertBlocks,
	// multiSelect,
	// removeBlocks,
	removeBlock,
	// insertDefaultBlock,
} = dispatch( 'core/editor' );
// } = dispatch( 'core/block-editor' ); -- uncomment once WP 5.2 released

const { getBlockHierarchyRootClientId, getBlockIndex, getBlock } = select(
	'core/editor'
);
// } = select( 'core/block-editor' ); -- uncomment once WP 5.2 released

/*
import classnames from 'classnames';
className={
	classnames( 'components-dropdown-menu__toggle', {
		'is-active': isOpen,
	} )
} */

export default class Designs extends React.Component {
	importCode = ( design, placeholderBlockId = false ) => {
		const { setUrl, name } = design;
		const remoteUrlSourceCode = setUrl + name + 'code.html';
		const remoteUrlStyles = setUrl + name + 'styles.css';
		fetch( remoteUrlSourceCode, {
			method: 'GET',
			// mode: 'no-cors',
			headers: { 'Content-Type': 'text/plain' },
			/* headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
			}, */
			// body: 'action=dsgn_design_import&_wpnonce=' + window.dsgnjs[ 'nonce' ] + '&design_set=basic',
			// credentials: 'same-origin'
		} ).then( response => {
			if ( response.ok ) {
				response.text().then( code => {
					// Import CSS
					fetch( remoteUrlStyles, {
						method: 'GET',
						headers: { 'Content-Type': 'text/plain' },
					} ).then( responseStyles => {
						if ( responseStyles.ok ) {
							responseStyles.text().then( css => {
								// Every design section should have unique CSS class and ID based on the design name.
								let cssClass = name.replace( new RegExp( '/', 'g' ), '-' );
								if ( '-' === cssClass.charAt( 0 ) ) {
									cssClass = cssClass.substr( 1 );
								}

								if ( '-' === cssClass.charAt( cssClass.length - 1 ) ) {
									cssClass = cssClass.substr( 0, cssClass.length - 1 );
								}

								// Replace generic dsgn__custom-class with our custom generated css class.
								code = code.replace(
									new RegExp( 'dsgn__custom-class', 'g' ),
									'dsgn__' + cssClass
								);
								css = css.replace(
									new RegExp( 'dsgn__custom-class', 'g' ),
									'dsgn__' + cssClass
								);

								let selectedBlockId = placeholderBlockId;
								if ( false === placeholderBlockId ) {
									const selectedBlock = getSelectedBlock();
									if ( selectedBlock ) {
										// If any block selected: add next to the selection.
										selectedBlockId = getSelectedBlock();
										// @docs: https://github.com/WordPress/gutenberg/blob/master/docs/designers-developers/developers/data/data-core-block-editor.md#getselectedblock
										selectedBlockId = selectedBlockId.clientId;
									}
								}
								// @docs: https://github.com/WordPress/gutenberg/blob/master/docs/designers-developers/developers/data/data-core-block-editor.md#getblockhierarchyrootclientid
								let rootBlockId = false;
								let rootBlockIndex = false;
								if ( selectedBlockId ) {
									rootBlockId = getBlockHierarchyRootClientId( selectedBlockId );
									// @docs: https://github.com/WordPress/gutenberg/blob/master/docs/designers-developers/developers/data/data-core-block-editor.md#getblockindex
									rootBlockIndex = getBlockIndex( rootBlockId );
								}
								// If added using drag and drop (placeholderId provided).
								if ( false !== placeholderBlockId ) {
									// Remove placeholder block.
									// @docs: https://github.com/WordPress/gutenberg/blob/master/docs/designers-developers/developers/data/data-core-block-editor.md#removeblock
									removeBlock( placeholderBlockId );
									// wp.data.dispatch( 'core/block-editor' ).removeBlock( placeholderBlockId );
								}
								// Unless dropping to the root:
								// insert design section bellow the current root section (+1).
								let blockShift = 1;
								if ( rootBlockId === placeholderBlockId ) {
									blockShift = 0;
								}
								// If no insertion point known add to the very end of the document.
								if ( false === rootBlockIndex ) {
									rootBlockIndex = 99999999;
								}
								// Insert new code into Gutenberg editor.
								// @docs: https://github.com/WordPress/gutenberg/blob/master/docs/designers-developers/developers/data/data-core-block-editor.md#insertblocks
								insertBlocks(
									wp.blocks.parse( code ),
									rootBlockIndex + blockShift
								);
								// wp.data.dispatch( 'core/block-editor' ).insertBlocks( wp.blocks.parse( code ), rootBlockIndex + blockShift );

								const inlineCSS = document.createElement( 'style' );
								inlineCSS.type = 'text/css';
								inlineCSS.innerHTML = css;
								document.body.appendChild( inlineCSS );

								fetch( window.ajaxurl, {
									method: 'POST',
									headers: {
										'Content-Type':
											'application/x-www-form-urlencoded; charset=utf-8',
									},
									body:
										'action=dsgn_ajax_save_css&_wpnonce=' +
										window.dsgnjs.nonce +
										'&dsgn_data=' +
										css +
										'&dsgn_id=' +
										cssClass +
										'&post_id=' +
										getCurrentPostId(),
									credentials: 'same-origin',
								} ).then( responseSaveCss => {
									if ( responseSaveCss.ok ) {
										responseSaveCss.text().then( responseCss => {
											if ( responseCss !== '1' ) {
												// eslint-disable-next-line no-console
												console.warn( 'ERROR SAVIG CSS:' );
												// eslint-disable-next-line no-console
												console.warn( response );
											}
										} );
									} else {
										const error = new Error( responseSaveCss.statusText );
										error.response = responseSaveCss;
										// eslint-disable-next-line no-console
										console.warn( error );
									}
								} );
							} );
						} else {
							const error = new Error( response.statusText );
							error.response = response;
							// eslint-disable-next-line no-console
							console.warn( error );
						}
					} );
				} );
			} else {
				const error = new Error( response.statusText );
				error.response = response;
				// eslint-disable-next-line no-console
				console.warn( error );
			}
		} );

		// wp.data.dispatch( 'core/editor' ).insertBlocks( wp.blocks.parse( '<!-- wp:columns {"columns":1} --><div class="wp-block-columns has-1-columns"><!-- wp:column --><div class="wp-block-column"><!-- wp:columns --><div class="wp-block-columns has-2-columns"><!-- wp:column --><div class="wp-block-column"><!-- wp:heading --><h2>Left </h2><!-- /wp:heading --><!-- wp:subhead --><p class="wp-block-subhead">Let\'s make it looks good</p><!-- /wp:subhead --><!-- wp:paragraph --><p>Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit sit amet non magna.</p><!-- /wp:paragraph --></div><!-- /wp:column --><!-- wp:column --><div class="wp-block-column"><!-- wp:heading --><h2>Right </h2><!-- /wp:heading --><!-- wp:subhead --><p class="wp-block-subhead">Let\'s make it looks good</p><!-- /wp:subhead --><!-- wp:paragraph --><p>Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit sit amet non magna.</p><!-- /wp:paragraph --></div><!-- /wp:column --></div><!-- /wp:columns --></div><!-- /wp:column --></div><!-- /wp:columns -->' ) );
	};

	dragStart = ( design, event ) => {
		event.dataTransfer.setData( 'text/html', '<strong>Loading...</strong>' );
	};

	drop = design => {
		const blockId = getSelectedBlock().clientId;
		const justInsertedBlock = getBlock( blockId ).attributes.content;
		if ( justInsertedBlock === '<strong>Loading...</strong>' ) {
			this.importCode( design, blockId );
		}
	};

	render() {
		const desginLibrary = this.props.data;
		return (
			<Fragment>
				{ Object.keys( desginLibrary ).map( ( setId, i ) => (
					<PanelBody
						title={ upperFirst( setId ) }
						initialOpen={ false }
						className={ 'design-category ' + 'id__' + kebabCase( setId ) }
						key={ i }
					>
						{ desginLibrary[ setId ].map( ( design, d ) => (
							<div className="design-item" key={ d }>
								<Button
									onClick={ () => {
										this.importCode( design );
									} }
									className="design-item__thumbnail"
									data-design-id={ design.name }
								>
									<img
										src={
											window.dsgnjs.uploadsUrl + design.name + 'thumbnail.png'
										}
										alt=""
										title={ design.name }
										onDragStart={ e => this.dragStart( design, e ) }
										onDragEnd={ e => this.drop( design, e ) }
									/>
								</Button>
								<div className={ 'design-item__bar' }>
									{ design.setId === 'premium' && (
										<span className={ 'design-item__pro' }>
											<Dashicon icon="awards" /> { __( 'Premium' ) }
										</span>
									) }
									{ /* <Button className="design-item__action" isDefault onClick={ () => { this.importCode( design ) }  }><Dashicon icon="arrow-down-alt" /> &nbsp;&nbsp;{ __( 'Insert' ) }</Button> */ }
									{ /* <Button className="design-item__preview" isDefault onClick={ () => { importCode() }  }><Dashicon icon="external" /> &nbsp;&nbsp;{ __( 'Preview' ) }</Button> */ }
									{ /* <Button className="design-item__info" isDefault onClick={ () => { importCode() }  }><Dashicon icon="warning" /></Button> */ }
									{ /* <Button className="design-item__fav" isDefault onClick={ () => { importCode() }  }><Dashicon icon="heart" /></Button> */ }
								</div>
							</div>
						) ) }
					</PanelBody>
				) ) }
			</Fragment>
		);
	}
}

// export default Designs
