import React from 'react';
import { connect } from 'react-redux';
import { dateI18n } from '@wordpress/date';
import fetch from 'unfetch';
import DesignsImporter from './designs-importer.jsx';

const { forEach, isEmpty } = window.lodash;
const { Fragment } = wp.element;
const { PanelBody, Dashicon, ExternalLink, Button } = wp.components;
const { __ } = wp.i18n;

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

class LibraryUpdate extends React.Component {
	constructor( props ) {
		super( props );

		this.state = {
			remoteDesignLibraryMeta: false,
			localDesignLibraryVersions: false,
			updateRequired: false,
		};
	}

	componentDidMount = () => {
		this.getRemoteLibraryStatus();
		this.setLocalDesignLibraryVersions();
	};

	componentDidUpdate = prevProps => {
		if ( prevProps.importing !== this.props.importing ) {
			this.setLocalDesignLibraryVersions();
		}
	};

	/**
	 * Update design set versions based on data
	 * received from the database on the initial page load.
	 */
	setLocalDesignLibraryVersions = () => {
		if ( ! isEmpty( window.dsgnjs.designLibrary ) ) {
			const versions = {};

			forEach( window.dsgnjs.designLibrary, ( designSet, setId ) => {
				if ( ! isEmpty( designSet.version ) ) {
					versions[ setId ] = designSet.version;
				}
			} );

			if ( ! isEmpty( versions ) ) {
				this.setState(
					{
						localDesignLibraryVersions: versions,
					},
					() => {
						this.updateLibraryStatus();
					}
				);
			}
		}
	};

	updateLibraryStatus = () => {
		let uptodate = true;
		forEach( this.state.remoteDesignLibraryMeta.versions, ( version, setId ) => {
			if (
				! isEmpty( this.state.localDesignLibraryVersions[ setId ] ) &&
				this.state.localDesignLibraryVersions[ setId ] !== version
			) {
				this.setState( {
					updateRequired: setId,
				} );

				uptodate = false;
				return false; // exit early to make sure we update one set at a time.
			}
		} );

		if ( this.state.updateRequired && uptodate ) {
			this.setState( {
				updateRequired: false,
			} );
		}
	};

	updateLibrary = () => {
		this.props.importDesigns( this.state.updateRequired );
	};

	getRemoteLibraryStatus = () => {
		fetch( 'https://wpdesignhub.com/designs/library-status.json', {
			method: 'GET',
			headers: {
				'Content-Type': 'text/plain',
			},
		} ).then( response => {
			if ( response.ok ) {
				response.json().then( remoteDesignLibraryMeta => {
					this.setState(
						{
							remoteDesignLibraryMeta: remoteDesignLibraryMeta,
						},
						() => {
							this.updateLibraryStatus();
						}
					);
				} );
			} else {
				const error = new Error( response.statusText );
				error.response = response;
				// eslint-disable-next-line no-console
				console.warn( error );
			}
		} );
	};

	render() {
		const { userStatus, importedSets, importing, designsCount } = this.props;

		return (
			<Fragment>
				<PanelBody
					title={ __( 'Design Library Update' ) }
					initialOpen={ userStatus }
					className={ 'dsgn__library-update' }
				>
					<Fragment>
						<div>
							{ isEmpty( importedSets ) && this.state.updateRequired && (
								<Button
									// icon="download"
									ref={ x => ( this._button_update_library = x ) }
									className="design-upsell__cta dsgn__library-download-new-designs"
									isBusy={ importing }
									isPrimary
									isLarge
									onClick={ () => {
										this._button_update_library.blur(); // Loading animation isn't working without blur.
										this.updateLibrary();
									} }
									disabled={ ! userStatus || ! this.state.updateRequired }
								>
									<Dashicon icon="download" /> { __( 'Download new designs' ) }
								</Button>
							) }
							<DesignsImporter getLibrary={ this.props.getLibrary } />

							{ 0 !== importedSets.length && (
								<Button
									className="design-upsell__cta dsgn__library-reset-versions"
									onClick={ () => {
										if ( window.dsgnjs.designLibrary.basic !== undefined ) {
											window.dsgnjs.designLibrary.basic.version = '0.0';
										}
										if ( window.dsgnjs.designLibrary.premium !== undefined ) {
											window.dsgnjs.designLibrary.premium.version = '0.0';
										}

										this.setLocalDesignLibraryVersions();
									} }
								>
									<Dashicon icon="download" /> { __( 'Reset version numbers' ) }
								</Button>
							) }

							<ul className="dsgn-settings__data">
								{ userStatus && (
									<li className="dsgn__library-status">
										<Dashicon icon="info" /> { __( 'Your library is ' ) }
										{ this.state.updateRequired && 0 !== designsCount && (
											<strong className="dsgn-outdated">
												{ __( 'outdated' ) }
											</strong>
										) }
										{ ! this.state.updateRequired &&
											50 >= designsCount &&
											0 !== designsCount && (
											<strong className="dsgn-outdated">
												{ __( 'not complete' ) }
											</strong>
										) }
										{ ! this.state.updateRequired && 50 < designsCount && (
											<strong className="dsgn-uptodate">
												{ __( 'up to date' ) }
											</strong>
										) }
										{ ! designsCount && (
											<strong className="dsgn-outdated">{ __( 'empty' ) }</strong>
										) }
									</li>
								) }
								<li>
									<Dashicon icon="chart-bar" /> { __( 'Released' ) }:
									<strong>
										{ ' ' +
											this.state.remoteDesignLibraryMeta.releasedDesigns +
											' ' +
											__( 'designs' ) }
									</strong>
									<ExternalLink
										href={
											'https://wpdesignhub.com/design-library/?utm_source=plugin-ui&utm_medium=sidebar&utm_campaign=plugins-settigns&utm_campaign=plugin-settings'
										}
										className="dsgn-settings__data-action-link"
									>
										{ __( 'library' ) }
									</ExternalLink>
								</li>
								<li>
									<Dashicon icon="calendar-alt" /> { __( 'Next Release' ) }:
									<strong>
										{ ' ' +
											dateI18n(
												'M d, Y',
												this.state.remoteDesignLibraryMeta.nextRelease
											) }
									</strong>
								</li>
							</ul>

							<p>
								{ __(
									'We are building the biggest design library for WordPress. Our target is to have 1000 premium designs by November 2019. Every second week we release new designs and raise the price of membership accordingly.'
								) }
							</p>
						</div>
					</Fragment>
				</PanelBody>
			</Fragment>
		);
	}
}

export default connect(
	// mapStateToProps:
	state => ( {
		userStatus: state.user.status,
		designsCount: state.designs.designsCount,
		importedSets: state.designs.importedSets,
	} ),
	//mapDispatchToProps:
	dispatch => ( {
		updateDesignsCount: count => {
			dispatch( setDesignsCount( count ) );
		},
		updateDesignLibrary: designs => {
			dispatch( setDesignLibrary( designs ) );
		},
	} )
)( LibraryUpdate );
