import * as React from 'react'
import cx from 'classnames'

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

import {
	BaseControl,
	Popover,
	Icon,
	Button,
} from '@wordpress/components'

import {
	help,
} from '@wordpress/icons'

import type {
	BaseControlProps,
} from '@wordpress/components/build-types/base-control/types'

import type {
	PopoverProps,
} from '@wordpress/components/build-types/popover/types'

import type {
	ButtonProps,
} from '@wordpress/components/build-types/button/types'

import './style.scss'

export interface WithTooltipProps extends BaseControlProps {
	label?: string
	buttonProps?: ButtonProps
	popoverProps?: PopoverProps & {className?: string}
	tooltip: React.ReactNode
}

const WithTooltip: React.FC<React.PropsWithChildren<WithTooltipProps>> = ({
	label = 'More info',
	tooltip,
	children,
	buttonProps,
	popoverProps,
	...props
}) => {

    const [isVisible, setIsVisible] = useState(false)

	return (
		<BaseControl
			className={cx('ska-components__with-tooltip', props?.className)}
			{...props}
			__nextHasNoMarginBottom
		>
			<Button
				label={label}
				onFocus={() => setIsVisible(true)}
				onBlur={() => setIsVisible(false)}
				onMouseEnter={() => setIsVisible(true)}
				onMouseLeave={() => setIsVisible(false)}
				{...buttonProps}
				className={cx('ska-components__with-tooltip__button', buttonProps?.className)}
				isPressed={isVisible}
			>
				<Icon icon={help} size={18} />
				{isVisible && (
					<Popover
						placement='top-end'
						focusOnMount={false}
						offset={8}
						animate={false}
						{...popoverProps}
						className={cx('ska-components__with-tooltip__popover', popoverProps?.className)}
						children={tooltip}
					/>
				)}
			</Button>
			{children}
		</BaseControl>
	)
}

export default WithTooltip
