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

import {
	hasBlockSupport,
	// @ts-expect-error
} from '@wordpress/blocks'

import {
	addFilter,
} from '@wordpress/hooks'

import {
	InspectorAdvancedControls,
	useBlockDisplayInformation,
	// @ts-expect-error
} from '@wordpress/block-editor'

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

import {
	createHigherOrderComponent,
} from '@wordpress/compose'

import type {
	tBlockEditProps,
	tBlockNameOrType,
} from '@ska/shared'

export interface RenameAttributes {
	metadata?: {
		name?: string
		bindings?: {
			source?: string
		}[]
	}
}

const hasRenameSupport = (block: tBlockNameOrType) => hasBlockSupport(block, 'renaming', true)

const RenameControls: React.FC<tBlockEditProps<RenameAttributes>> = (props) => {

	const {
		clientId,
		attributes,
		setAttributes,
	} = props

	const {
		metadata = {},
	} = attributes

	const blockInformation = useBlockDisplayInformation(clientId)
	const originalBlockName = blockInformation?.title || ''

	const customName = metadata?.name || ''
	const hasPatternOverrides = (
		!!customName
		&& !!metadata?.bindings
		&& Object.values(metadata.bindings).some(binding => binding.source === 'core/pattern-overrides')
	)
	const hasOverridesWarning = hasPatternOverrides

	return <>
		<InspectorAdvancedControls>
			<TextControl
				label={__('Block name', 'ska-blocks')}
				help={hasOverridesWarning
					? __('This block allows overrides. Changing the name can cause problems with content entered into instances of this pattern.')
					: __('Custom display name for this block.', 'ska-blocks')}
				placeholder={originalBlockName}
				value={customName}
				onChange={nextValue => {
					if(customName !== nextValue) {
						if(!nextValue && Object.keys(metadata).length === 1 && Object.keys(metadata)[0] === 'name') {
							setAttributes({metadata: undefined})
						} else {
							setAttributes({
								metadata: {
									...metadata,
									name: nextValue,
								},
							})
						}
					}
				}}
				__nextHasNoMarginBottom
				__next40pxDefaultSize
			/>
		</InspectorAdvancedControls>
	</>
}

const withRenameControls = createHigherOrderComponent(
	(BlockEdit: any) => (props: tBlockEditProps) => {
		if(hasRenameSupport(props.name)) {
			return <>
				<RenameControls {...props as any as tBlockEditProps<RenameAttributes>} />
				<BlockEdit {...props} />
			</>
		}
		return <BlockEdit {...props} />
	},
	'withSkaBlocksRenameControls'
)

export default () => {
	addFilter('editor.BlockEdit', 'ska-blocks/with-rename-controls', withRenameControls, -300)
}
