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

import { baseUrl } from '@/globals';
import { IForm } from '@/types';

interface IDialogProps {
	setOpen: ( val: boolean ) => void;
  onSelectForm: ( form: IForm ) => void;
}

class SelectDialog extends React.Component<IDialogProps> {
	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.props.setOpen( false );
		}
	};

	render() {
		return (
			<Modal
				title="Cognito Forms"
				className="cognito-modal"
				onRequestClose={ () => this.props.setOpen( false ) }
				shouldCloseOnClickOutside={ false }
			>
				<iframe
					style={ { width: '500px', height: '100%', display: 'block' } }
					src={ `${ baseUrl }/integrations/cms` }
					title="Choose a Form"
				></iframe>
			</Modal>
		);
	}
}

export default SelectDialog;
