import * as React from 'react'

import {
	Button,
	Modal,
} from '@wordpress/components'

import {
	useState,
} from '@wordpress/element'

export interface ModalButtonProps {
	/** Button text. */
	label?: string
	/** Button icon. */
	icon?: any
	/** Button state. */
	disabled?: boolean
	/** Button size. */
	size?: 'small' | 'default' | 'compact'
	/** Button icon size. */
	iconSize?: number
	/** Modal title. */
	title?: string
	/** Other modal props. */
	modalProps?: any
	/** Modal content. */
	children?: React.ReactNode
	/** Get modal content. */
	getChildren?: () => React.ReactNode
}

const ModalButton: React.FC<ModalButtonProps> = ({
	label,
	title,
	children,
	getChildren,
	modalProps = {},
	...props
}) => {

	const [isOpen, setIsOpen] = useState(false)

	return <>
		<Button
			onClick={() => setIsOpen(true)}
			children={label}
			{...props}
		/>
		{isOpen && (
			<Modal
				title={title}
				{...modalProps}
				onRequestClose={() => setIsOpen(false)}
				children={getChildren ? getChildren() : children}
			/>
		)}
	</>
}

export default ModalButton
