import React from 'react';
import { connect } from 'react-redux'; // https://react-redux.js.org/introduction/quick-start

import { setUserStatus } from './actions/user-actions';

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

import { setCurrentPanel } from './actions/ui-actions';

import Designs from './designs.jsx';
import UpsellPanel from './upsell-panel.jsx';
import Settings from './settings.jsx';
import fetch from 'unfetch';

const { forEach, isEmpty, set, isArray } = window.lodash;
const { Fragment } = wp.element;

// https://github.com/WordPress/gutenberg/blob/3450273fe7522101e3809b270c80a7b9a3ebcf3a/packages/compose/src/with-state/README.md
// import { withState } from '@wordpress/compose';
const { __ } = wp.i18n;

class Sidebar extends React.Component {
	/**
	 * Import design library data from WP database into React
	 */
	getLibrary = () => {
		fetch( window.ajaxurl, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
			},
			body: 'action=dsgn_get_library&_wpnonce=' + window.dsgnjs.nonce,
			credentials: 'same-origin',
		} )
			.then( response => {
				// return response.json();

				if ( response.ok ) {
					return response.json();
				}
				const error = new Error( response.statusText );
				error.response = response;
				// eslint-disable-next-line no-console
				console.warn( error );
			} )
			.then( json => {
				this.updateLibraryData( json );
			} );
	};

	updateLibraryData = data => {
		if ( ! isEmpty( data.basic ) ) {
			this.props.updateImportedSets( 'basic' );
		}

		if ( ! isEmpty( data.premium ) ) {
			this.props.updateImportedSets( 'premium' );
		}

		window.dsgnjs.designLibrary = data;

		let totalDesigns = 0;

		// Transform provided data object into the one with designs sorted by category.
		const designsByCategory = {};
		forEach( data, ( designSet, designSetId ) => {
			if ( designSet.designs.length ) {
				forEach( designSet.designs, function( design ) {
					if ( design.categories.length ) {
						forEach( design.categories, function( category ) {
							if ( ! isArray( designsByCategory[ category ] ) ) {
								set( designsByCategory, '[' + category + ']', [] );
							}

							designsByCategory[ category ].push( {
								name: design.name,
								categories: design.categories,
								setId: designSetId,
								setName: designSet.name,
								setPrice: designSet.price,
								setUrl: designSet.base_url,
							} );
						} );
					}
					totalDesigns++;
				} );
			}
		} );

		this.props.updateDesignLibrary( designsByCategory );
		this.props.updateDesignsCount( totalDesigns );
	};

	componentDidMount() {
		this.updateLibraryData( window.dsgnjs.designLibrary );
		this.setUserStatusByLicense( window.dsgnjs.license );
	}

	/**
	 * Set userStatus flag on panel render based on data pased from php.
	 *
	 * @function setUserStatusByLicense
	 * @param  {object} license License data object.
	 * @return {void}
	 */
	setUserStatusByLicense = license => {
		if ( 'valid' === license.license ) {
			const currentLicenseLimit = license.license_limit;
			// User roles.
			if ( currentLicenseLimit < 3 ) {
				this.props.updateUserStatus( 'personal' );
			} else if ( currentLicenseLimit < 100 ) {
				this.props.updateUserStatus( 'developer' );
			} else if ( currentLicenseLimit < 200 ) {
				this.props.updateUserStatus( 'studio' );
			} else {
				this.props.updateUserStatus( 'premium' );
			}
		} else {
			this.props.updateUserStatus( false );
		}
	};

	switchPanels = panelId => {
		this.props.updateCurrentPanel( panelId );
	};

	render() {
		const { errorMessage, currentPanel, designLibrary } = this.props;
		return (
			<Fragment>
				<ul className="sidebar__panel-tabs">
					<li>
						<button
							onClick={ () => this.switchPanels( false ) }
							className={
								'edit-post-sidebar__panel-tab ' +
								( currentPanel ? '' : 'is-active' )
							}
							aria-label={ __( 'Designs' ) }
							data-label={ __( 'Designs' ) }
						>
							{ __( 'Designs' ) }
						</button>
					</li>
					<li>
						<button
							onClick={ () => this.switchPanels( 'styles' ) }
							className={
								'edit-post-sidebar__panel-tab ' +
								( 'styles' === currentPanel ? 'is-active' : '' )
							}
							aria-label={ __( 'Styles' ) }
							data-label={ __( 'Styles' ) }
						>
							{ __( 'Styles' ) }
						</button>
					</li>
					<li>
						<button
							onClick={ () => this.switchPanels( 'settings' ) }
							className={
								'edit-post-sidebar__panel-tab ' +
								( 'settings' === currentPanel ? 'is-active' : '' )
							}
							aria-label={ __( 'Settings' ) }
							data-label={ __( 'Settings' ) }
						>
							{ __( 'Settings' ) }
						</button>
					</li>
				</ul>

				{ ! currentPanel && (
					<UpsellPanel
						errorMessage={ errorMessage }
						getLibrary={ this.getLibrary }
					/>
				) }
				{ ! currentPanel && ! isEmpty( designLibrary ) && (
					<Designs data={ designLibrary } />
				) }
				{ ! currentPanel && isEmpty( designLibrary ) && (
					<a
						href="https://wpdesignhub.com/pro/?utm_source=plugin-ui&utm_medium=sidebar&utm_campaign=installer-empty-state&utm_campaign=installer-empty-state"
						target="_blank"
						rel="noreferrer noopener"
						className="dsgn__empty-state"
					>
						<img src={ window.dsgnjs.pluginUrl + '/assets/bunnya.png' } alt="" />
					</a>
				) }

				{ 'styles' === currentPanel && (
					<a
						href="/wp-admin/plugin-install.php?s=StylistWp&tab=search&type=term"
						target="_blank"
						rel="noreferrer noopener"
						className="dsgn__stylist"
					>
						<img
							src={ window.dsgnjs.pluginUrl + '/assets/styling-tab.png' }
							alt=""
						/>
					</a>
				) }
				{ 'settings' === currentPanel && (
					<Settings
						setUserStatusByLicense={ this.setUserStatusByLicense }
						getLibrary={ this.getLibrary }
					/>
				) }
			</Fragment>
		);
	}
}

export default connect(
	// mapStateToProps
	state => ( {
		designLibrary: state.designs.designLibrary,
		designsCount: state.designs.designsCount,
		userStatus: state.user.status,
		currentPanel: state.ui.currentPanel,
	} ),
	//mapDispatchToProps
	( dispatch ) => ( {
		updateDesignsCount: count => {
			dispatch( setDesignsCount( count ) );
		},
		updateDesignLibrary: designs => {
			dispatch( setDesignLibrary( designs ) );
		},
		updateUserStatus: newStatus => {
			dispatch( setUserStatus( newStatus ) );
		},
		updateCurrentPanel: panelId => {
			dispatch( setCurrentPanel( panelId ) );
		},
		updateImportedSets: setId => {
			dispatch( addImportedSets( setId ) );
		},
	} )
)( Sidebar );
