import { useLayoutEffect, useState } from '@wordpress/element';
import clsx from '../../../utils/clsx';
import { Icon } from '../Icon';

const Popover = ( {
	id,
	style,
	className,
	content,
	trigger = 'always',
	position = 'right-center',
	arrowPosition = 'left-center',
} ) => {
	const [ isOpen, setIsOpen ] = useState( false );

	useLayoutEffect( () => {
		setIsOpen( trigger === 'always' );
	}, [ trigger ] );

	return (
		<div
			id={ id }
			style={ style }
			className={ clsx( 'rbfb-popover', position, className ) }
		>
			<div
				className="rbfb-popover-dot"
				onMouseEnter={ () => trigger === 'hover' && setIsOpen( true ) }
				onMouseLeave={ () => trigger === 'hover' && setIsOpen( false ) }
				onClick={ () => setIsOpen( () => ! isOpen ) }
			/>

			<div
				className={ clsx(
					'rbfb-popover-content',
					`rbfb-arrow-${ arrowPosition }`,
					{
						'rbfb-popover-visible': isOpen,
					}
				) }
			>
				<Icon
					name="close"
					color="gray-400"
					style={ {
						position: 'absolute',
						top: '8px',
						right: '8px',
						zIndex: 3,
						cursor: 'pointer',
					} }
					onClick={ () => setIsOpen( false ) }
				/>

				{ content }
			</div>
		</div>
	);
};

export default Popover;
