import * as React from 'react'
import {__, _x} from '@wordpress/i18n'
import cx from 'classnames'

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

import {
	Popover,
} from '@wordpress/components'

import {
	useSelect,
} from '@wordpress/data'

import {
	store as editPostStore,
	// @ts-expect-error
} from '@wordpress/edit-post'

import {
	useClickAway,
} from 'react-use'

import {
	usePluginPreference,
} from '../../../store'

import {
	IS_SETTINGS_PAGE,
} from '@ska/utils'

import './style.scss'

const noop = () => {}

export interface DropdownProps {
	className?: string
	contentClassName?: string
	renderToggle: (inheritedProps: {onToggle: () => void, isOpen: boolean}) => React.ReactElement
	renderContent: () => React.ReactElement
}

const Dropdown: React.FC<DropdownProps> = (props) => {

	const {
		className,
		contentClassName,
		renderToggle,
		renderContent,
	} = props

	const sidebarOpened = useSelect(select => select(editPostStore).isPluginSidebarOpened(), [])
	const [sidebarExpanded] = usePluginPreference('sidebarExpanded')
	const wideSidebar = sidebarOpened && sidebarExpanded
	/** On settings page the settings are full screen, while normally the popover opens in a right sidebar. */
	const PLACEMENT = IS_SETTINGS_PAGE || wideSidebar ? 'top-start' : 'left'
	const OFFSET = IS_SETTINGS_PAGE || wideSidebar ? 4 : 24

	const [isOpen, setIsOpen] = useState(false)
	const toggle = () => setIsOpen(!isOpen)
	const close = () => setIsOpen(false)

	const contentRef = useRef(null)

	useClickAway(contentRef, (e) => {

		if(
			!isOpen
			// @ts-expect-error
			|| e?.target?.classList?.contains('components-popover__content')
			// @ts-expect-error
			|| e?.target?.classList?.contains('ska-blocks__toggle-button--is-open')
		) {
			return
		}

		close()
	})

	return (
		<div
			className={cx('components-dropdown', 'ska-blocks__dropdown', className)}
			tabIndex={-1}
		>
			{renderToggle({isOpen, onToggle: toggle})}
			{isOpen && (
				<Popover
					className={cx('components-dropdown__content', 'ska-blocks__dropdown__content', contentClassName)}
					shift
					resize={false}
					placement={PLACEMENT}
					onClose={close}
					onFocusOutside={noop}
					offset={OFFSET}
				>
					<div
						className='ska-blocks__dropdown__content__wrapper ska-blocks--use-global-theme'
						ref={contentRef}
					>
						{renderContent()}
					</div>
				</Popover>
			)}
		</div>
	)
}

export default Dropdown
