import * as React from 'react'

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

import {
	__experimentalLinkControl as LinkControl,
	// @ts-expect-error
} from '@wordpress/block-editor'

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

import {
	displayShortcut,
	rawShortcut,
} from '@wordpress/keycodes'

import {
	link,
	linkOff,
} from '@wordpress/icons'

const noop = () => {}

import './style.scss'

export interface URLPickerStrings {
	linkButtonLabel: string
	unlinkButtonLabel: string
}
export const URL_PICKER_STRINGS = {
	linkButtonLabel: 'Link',
	unlinkButtonLabel: 'Unlink',
}
export const URLPickerStringsContext = createContext<URLPickerStrings>(URL_PICKER_STRINGS)

export interface LinkControlValue {
	id?: number
	kind?: string | 'post-type'
	type?: string | 'page' | 'post'
	title?: string
	url?: string
	opensInNewTab?: boolean
}

export interface URLPickerProps {
	value?: string
	onChange?: (nextValue: string, linkValue: LinkControlValue) => void
	opensInNewTab?: boolean
	onToggleOpensInNewTab?: () => void
	keyboardShortcuts?: boolean
	renderControlBottom?: React.ReactNode | null
}

const URLPicker: React.FC<URLPickerProps> = ({
	value = '',
	onChange = noop,
	opensInNewTab = false,
	onToggleOpensInNewTab = noop,
	keyboardShortcuts = true,
	renderControlBottom = null,
}) => {

	const {
		linkButtonLabel,
		unlinkButtonLabel,
	} = useContext(URLPickerStringsContext)

	const [isOpen, setIsOpen] = useState(false)

	return <>
		<ToolbarButton
			icon={link}
			title={linkButtonLabel}
			shortcut={keyboardShortcuts ? displayShortcut.primary('k') : undefined}
			isActive={isOpen || !!value}
			onClick={() => setIsOpen(true)}
		/>
		{value && (
			<ToolbarButton
				icon={linkOff}
				title={unlinkButtonLabel}
				shortcut={keyboardShortcuts ? displayShortcut.primaryShift('k') : undefined}
				onClick={() => onChange('', {})}
			/>
		)}
		{isOpen && (
			<Popover
				placement='bottom'
				onClose={() => setIsOpen(false)}
			>
				<LinkControl
					className='ska-components__link-control'
					value={{
						url: value,
						opensInNewTab,
					}}
					onChange={(linkValue: LinkControlValue = {}) => {
						const {
							url: nextValue = '',
							opensInNewTab: nextOpensInNewTab,
						} = linkValue
						if(value !== nextValue) {
							onChange(nextValue, linkValue)
						}
						if(opensInNewTab !== nextOpensInNewTab) {
							onToggleOpensInNewTab()
						}
					}}
					renderControlBottom={renderControlBottom ? () => (
						<div className='ska-components__link-control__bottom'>{renderControlBottom}</div>
					) : null}
					hasRichPreviews={false}
				/>
			</Popover>
		)}
		{keyboardShortcuts && (
			<KeyboardShortcuts
				bindGlobal
				shortcuts={{
					[rawShortcut.primary('k')]: () => setIsOpen(true),
					[rawShortcut.primaryShift('k')]: () => onChange('', {}),
				}}
			/>
		)}
	</>
}

export default URLPicker
