import React from 'react';
import { connect } from 'react-redux';
import fetch from 'unfetch';

const { Fragment } = wp.element;
const { PanelBody, Dashicon, Button } = wp.components;
const { __ } = wp.i18n;

import {
	emptyImportedSets,
	setDesignLibrary,
	setDesignsCount,
} from './actions/designs-actions';

class AdvancedSettings extends React.Component {
	constructor( props ) {
		super( props );
		this.state = {
			deletingLibrary: false,
		};
	}

	deleteLibrary = () => {
		this.setState( { deletingLibrary: true } );
		fetch( window.ajaxurl, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
			},
			body: 'action=dsgn_delete_library&_wpnonce=' + window.dsgnjs.nonce,
			credentials: 'same-origin',
		} ).then( response => {
			if ( response.ok ) {
				window.dsgnjs.designLibrary = {};
				this.setState( { deletingLibrary: false } );
				this.props.removeImportedSets();
				this.props.updateDesignLibrary( false );
				this.props.updateDesignsCount( 0 );
			} else {
				const error = new Error( response.statusText );
				error.response = response;
				// eslint-disable-next-line no-console
				console.warn( error );
			}
		} );
	};

	render() {
		return (
			<Fragment>
				<PanelBody
					title={ __( 'Advanced Settings' ) }
					initialOpen={ false }
					className={ 'dsgn__advanced-settings' }
				>
					<Fragment>
						<div>
							<Button
								ref={ x => ( this._button_delete_library = x ) }
								className="design-upsell__cta dsgn__delete-library dsgn__delete-action"
								isBusy={ this.state.deletingLibrary }
								isLarge
								onClick={ () => {
									this._button_delete_library.blur(); // Loading animation isn't working without blur.
									this.deleteLibrary();
								} }
								disabled={ this.props.designsCount === 0 }
							>
								<Dashicon icon="trash" /> { __( 'Delete imported designs' ) }
							</Button>
						</div>
					</Fragment>
				</PanelBody>
			</Fragment>
		);
	}
}

export default connect(
	// mapStateToProps:
	state => ( {
		designsCount: state.designs.designsCount,
	} ),
	//mapDispatchToProps:
	dispatch => ( {
		updateDesignsCount: count => {
			dispatch( setDesignsCount( count ) );
		},
		updateDesignLibrary: designs => {
			dispatch( setDesignLibrary( designs ) );
		},
		removeImportedSets: () => {
			dispatch( emptyImportedSets() );
		},
	} )
)( AdvancedSettings );
