import { LabelControl } from './label';
import { useState, useRef, useEffect } from '@wordpress/element';
import { Popover } from '@wordpress/components';

export const ModalControl = (props) => {
	const { prop, children, label } = props;
	const { width } = prop;

	const [isModalVisible, setIsModalVisible] = useState(false);
	const modalRef = useRef(null);
	const modalIconRef = useRef(null);

	useEffect(() => {
		const handleDocumentClick = (e) => {

			// Access Modal Handler
			if (
				modalRef.current &&
				!modalRef.current.contains(e.target) &&
				modalIconRef.current &&
				!modalIconRef.current.contains(e.target)
			) {
				setIsModalVisible(false);
			}
		};

		document.addEventListener('click', handleDocumentClick);
		return () => {
			document.removeEventListener('click', handleDocumentClick);
		};
	}, []);
	
	var style = pagelayer_empty(width) ? {} : {width: width};
	
	return (
		<div className="components-base-control pagelayer-base-control">
			<LabelControl {...props} />
			<div className="pagelayer-elp-modal-div">
				<span
					className="pagelayer-elp-modal"
					onClick={() => setIsModalVisible(true)}
					ref={ modalIconRef }
				>
					<i className={`pli pli-window`}></i>
				</span>
				{isModalVisible && ( 
						<Popover className="pagelayer-elp-modal-wrapper" position="top-start">
							<div className="pagelayer-elp-modal-wrap" style={style} ref={ modalRef }>
								<div className="pagelayer-elp-modal-header">
									{ label }
									<i className="pagelayer-elp-modal-close pli pli-cross" aria-hidden="true" onClick={() => setIsModalVisible(false)}></i>
								</div>
								<hr />
								<div className="pagelayer-elp-modal-holder">
									{ children }
								</div>
							</div>
					</Popover>
				) }
			</div>
		</div>
	)
}