/**
 * WordPress dependencies
 */
import * as React from 'react';
import { Button, Modal, FocusableIframe } from '@wordpress/components';

import { baseUrl } from '@/globals';

type DialogProps = {
  onSelectForm: Function;
};

type DialogState = {
  isOpen: boolean;
};

class SelectDialog extends React.Component<DialogProps, DialogState> {
	constructor( props: any ) {
		super( props );

		this.state = {
			isOpen: false,
		};
	}

	componentDidMount() {
		window.addEventListener( 'message', this.handlePostMessage, false );
	}

	componentWillUnmount() {
		window.removeEventListener( 'message', this.handlePostMessage );
	}

	handlePostMessage = ( event: MessageEvent ) => {
		if (event.origin === baseUrl && event.data.type === 'cog-form-selected') {
			this.props.onSelectForm( event.data );
			this.setState({ isOpen: false }); // Close Dialog
		}
	}

	render() {
		return (
			<div>
				<Button isPrimary={true} onClick={ () => this.setState( { isOpen: true } ) }>
					Choose a form
				</Button>
				{ this.state.isOpen && (
					<Modal
						title="Cognito Forms"
						className="cognito-modal"
						onRequestClose={ () => this.setState( { isOpen: false } ) }
						shouldCloseOnClickOutside={ false }
					>
						<FocusableIframe
							style={ { width: '500px', height: '500px', display: 'block' } }
							src={ `${ baseUrl }/integrations/cms` }
						></FocusableIframe>
					</Modal>
				) }
			</div>
		);
	}
}

export default SelectDialog;
