import Button from './Button';
import './EditableLinkItem.scss';

const EditableLinkedItem = ({ label, buttonText, entityType, entityId, element = 'button' }) => {

	/**
	 * This handler creates and dispatches the custom event to open the modal
	 * in "inline navigation" mode.
	 */
	const handleEditClick = () => {
		if (!entityType || !entityId) return;

		const openModalEvent = new CustomEvent('adpresso:openEditModal', {
			bubbles: true,
			detail: {
				entityType: entityType,
				entityId: entityId,
				isInlineNavigation: true,
			}
		});

		document.body.dispatchEvent(openModalEvent);
	};

	return (
		<div className="adpresso-editable-linked-item">
			<span className="item-label">{label}</span>
			{element === 'button' ? (
				<Button
					variant="secondary"
					onClick={handleEditClick}
					disabled={!entityId}
				>
					{buttonText}
				</Button>
			) : (
				<a
					href="#"
					onClick={handleEditClick}
					className="adpresso-link"
				>
					{buttonText}
				</a>
			)}
		</div>
	);
};

export default EditableLinkedItem;
