/**
 * WordPress dependencies
 */
import * as React from 'react';
import * as _ from 'lodash';

import { Spinner } from '@wordpress/components';

import { baseUrl } from '@/globals';
import { ReactComponent as CogIcon } from '@/../cogicon.svg';

interface IPreviewProps {
	embedCode: string;
}

interface IPreviewState {
	uniqueId: string;
	loading: boolean;
}

class PreviewForm extends React.Component<IPreviewProps, IPreviewState> {
	constructor( props: IPreviewProps ) {
		super( props );

		// Generate a unique identifier, so that the embed script can be identified
		// and removed from the page once it is no longer needed.
		this.state = {
			uniqueId: _.uniqueId(),
			loading: true,
		};
	}

	componentDidMount() {
		this.loadEmbedScript( this.formReady.bind( this ) );
	}

	componentWillUnmount() {
		this.removeEmbedScript();
	}

	// Force the embed script to load, which makes Iframes in the editor resize properly.
	loadEmbedScript( callback?: () => void ) {
		const existingScript = document.getElementById( `cog-embed-script-${ this.state.uniqueId }` );

		if ( ! existingScript ) {
			const script = document.createElement( 'script' );
			script.src = `${ baseUrl }/f/iframe.js`;
			script.id = `cog-embed-script-${ this.state.uniqueId }`;
			document.body.appendChild( script );

			script.onload = () => {
				if ( callback ) callback();
			};
		}

		if ( existingScript && callback ) callback();
	}

	// Clean up before block is removed
	removeEmbedScript() {
		const existingScript = document.getElementById( `cog-embed-script-${ this.state.uniqueId }` );

		if ( existingScript ) {
			existingScript.remove();
		}
	}

	// Check if form is loaded
	formReady() {
		this.setState( { loading: false } );
	}

	render() {
		return (
			<div className="form-preview">
				<div className="focus-grabber"></div>
				{ this.state.loading &&
					<div className="loader">
						<div className="icon">
							<CogIcon />
						</div>

						<p>
							Loading...
						</p>

						<Spinner />
					</div>
				}
				<div
					className="cog-wp-embed cog-wp-embed__preview"
					dangerouslySetInnerHTML={ { __html: this.props.embedCode } } // Must be Iframe embed code as others do not work in Gutenberg
					id={ `cog-form-${ this.state.uniqueId }` }
				></div>
			</div>
		);
	}
}

export default PreviewForm;
